Andres Azqueta - 9 months ago 110

Python Question

I have 291*291 matrix and I will like to automatically retrieved only the values (0,1), (1,2), (2,3).... (n-1, n). Is there a straight forward way to do it using loops or a function?

The matrix is the cosine-similarity between texts in a data base such:

`bodies = [d['body'] for d in data]`

tfidf = vectorizer.fit_transform(bodies)

matrix =(tfidf * tfidf.T).A

Since I want to create a vector this is how I am attempting to do it:

`vector = []`

for i in range(len(data) -1):

vector.append(matrix(i, i+1))

But I get the following error:

`TypeError: 'numpy.ndarray' object is not callable`

Any ideas of how to fix it?

kind regards,

Answer

As your matrix is square, you can use `numpy.diagonal`

with an offset of 1 to acquire your desired values

```
mat.diagonal(offset = 1)
```

The positive offset of 1 acquires the diagonal 1 above the matrix's main diagonal.

*Mini demo*:

```
mat = numpy.ones((3,3))
mat[0,1] = 2
mat[1,2] = 3
print(mat.diagonal(offset = 1))
```

Outputs:

```
[ 2. 3.]
```