numpy.savetxt IndexError:元组索引超出范围

时间:2014-12-06 02:12:59

标签: csv python-3.x numpy

我有一个具有以下属性的numpy数组:

print(matrix.shape)
(30000, 1000)

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

当我尝试将数组写入文件时,我得到:

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

我做错了什么?

1 个答案:

答案 0 :(得分:2)

print(matrix)的输出显然matrixscipy.sparse.coo_matrix的实例。这样的矩阵不是一个numpy数组; numpy对scipy稀疏矩阵一无所知。特别是,numpy.savetxt不能处理scipy的稀疏矩阵。

有关如何将稀疏矩阵保存到文本文件的建议,请参阅我在此处对其他问题的回答:How to format in numpy savetxt such that zeros are saved only as "0"