+3 votes
in Programming Languages by (74.2k points)

I am trying to print the length (number of rows) of a CSR matrix, but the code is throwing the following error:

Traceback (most recent call last):

    print("Number of records in the new dataset...{0}, {1}, {2}".format(len(X_new), len(Y_new), len(pids_new)))

  File "/usr/local/lib64/python3.6/site-packages/scipy/sparse/base.py", line 295, in __len__

    raise TypeError("sparse matrix length is ambiguous; use getnnz()"

TypeError: sparse matrix length is ambiguous; use getnnz() or shape[0]

How can I find the number of rows in the CSR matrix?

1 Answer

+1 vote
by (351k points)
selected by
 
Best answer

You cannot use the len() function to find the number of rows in a CSR matrix. You should use shape; it will return the number of rows and columns in the CSR matrix.

Here is an example:

>>> from scipy.sparse import csr_matrix
>>> import numpy as np
>>> row = np.array([0, 0, 1, 2, 2, 2])
>>> col = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 1, 1, 1, 1, 1])
>>> X=csr_matrix((data, (row, col)), shape=(3, 3))
>>> X.shape
(3, 3)
>>> rows=X.shape[0]
>>> cols=X.shape[1]
>>> rows
3
>>> cols
3


...