我是 Python 的新手,我正在尝试将矩阵中的数据写入 CSV 文件。变量定义为:
(Pdb) trainFeatures
<1562936x312116 sparse matrix of type '<type 'numpy.float64'>'
with 43753231 stored elements in Compressed Sparse Row format>
我有一行代码:
numpy.savetxt("feature_train.csv", trainFeatures, delimiter=',')
当我运行该行时,我收到一条错误消息:
ncol = X.shape[1]
IndexError: tuple index out of range
我确定矩阵的格式不正确,但我不知道如何得到它。谁能指出我需要在这里做什么?
最佳答案
Ok,完成这个过程,原题的答案是使用todense()方法将trainFeatures转成savetxt()可以识别的格式。但是要对内存不足做进一步的评论,显而易见的解决方案是使用 getrow() 方法并遍历所有行并将每一行单独写入文件,而不是尝试一次性完成整个矩阵。
关于python - 无法将稀疏矩阵写入 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25130156/