2

I have a numpy array with the following attributes:

print(matrix.shape)
(30000, 1000)

print(matrix)
(0, 208)      0.107297742751
(0, 666)      0.107413554001
(0, 833)      0.090485141939
(0, 616)      0.090485141939
..
..

When I try to write the array to a file I get:

numpy.savetxt('matrix.csv', matrix, delimiter=',')
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-18-412b5d26d905> in <module>()
----> 1 numpy.savetxt('matrix.csv', matrix, delimiter=',')

C:\Anaconda3\lib\site-packages\numpy\lib\npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments)
   1042                 ncol = len(X.dtype.descr)
   1043         else:
-> 1044             ncol = X.shape[1]
   1045 
   1046         iscomplex_X = np.iscomplexobj(X)

IndexError: tuple index out of range

What am I doing wrong?

2

1 Answer 1

2

From the output of print(matrix), it is apparent that matrix is an instance of scipy.sparse.coo_matrix. Such a matrix is not a numpy array; numpy knows nothing about scipy sparse matrices. In particular, numpy.savetxt doesn't handle scipy's sparse matrices.

For a suggestion on how to save a sparse matrix to a text file, see my answer to a different question here: How to format in numpy savetxt such that zeros are saved only as "0"

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.