numpy.savetxt IndexError:tuple index超出范围 [英] numpy.savetxt IndexError: tuple index out of range
问题描述
我有一个numpy数组,具有以下属性:
print(matrix.shape)
(30000, 1000)
print(matrix)
(0,208)0.107297742751
(0,666)0.107413554001
(0,833)0.090485141939
,616)0.090485141939
..
..
数组到文件我获得:
numpy.savetxt('matrix.csv',matrix,delimiter =',')
---------------------------------------------- -----------------------------
IndexError Traceback(最近一次调用)
< ipython-input -18-412b5d26d905> in< module>()
----> 1 numpy.savetxt('matrix.csv',matrix,delimiter =',')
C:\Anaconda3\lib\site-packages\\\
umpy\lib\\\
pyio。 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超出范围
我做错了什么?
解决方案p>从
print(matrix)
的输出,显然matrix
是scipy.sparse.coo_matrix
。这样的矩阵不是numpy数组; numpy对scipy稀疏矩阵一无所知。特别是numpy.savetxt
不处理scipy的稀疏矩阵。
有关如何保存稀疏矩阵到文本文件,请参阅我的回答不同的问题在这里:如何在numpy savetxt中格式化,使得零仅保存为0
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?
解决方案From the output of
print(matrix)
, it is apparent thatmatrix
is an instance ofscipy.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"
这篇关于numpy.savetxt IndexError:tuple index超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!