我在使用PyTables存储numpy csr_matrix时遇到问题 . 我收到这个错误:
TypeError: objects of type ``csr_matrix`` are not supported in this context, sorry; supported objects are: NumPy array, record or scalar; homogeneous list or tuple, integer, float, complex or string
我的代码:
f = tables.openFile(path,'w')
atom = tables.Atom.from_dtype(self.count_vector.dtype)
ds = f.createCArray(f.root, 'count', atom, self.count_vector.shape)
ds[:] = self.count_vector
f.close()
有任何想法吗?
谢谢
3 回答
CSR矩阵可以从其
data
,indices
和indptr
属性完全重建 . 这些只是常规的numpy数组,因此将它们存储为pytables中的3个独立数组应该没有问题,然后将它们传递回csr_matrix
的构造函数 . 见scipy docs .Edit: Pietro的回答指出
shape
成员也应该存储DaveP的答案几乎是正确的......但是可能会导致非常稀疏的矩阵出现问题:如果最后一列或一行是空的,它们会被丢弃 . 因此,为了确保一切正常,"shape"属性也必须存储 .
这是我经常使用的代码:
将其适应csc矩阵是微不足道的 .
我更新了Pietro Battiston对Python 3.6和PyTables 3.x的优秀答案,因为一些PyTables函数名称在2.x升级中已经改变 .