在处理一些文本数据时,我试图将一个 np 数组(来自 pandas 系列)连接到一个 csr 矩阵。
我已经完成了以下操作。
#create a compatible sparse matrix from my np.array.
#sparse.csr_matrix(X['link'].values) returns array size (1,7395)
#transpose that array for (7395,1)
X = sparse.csr_matrix(X['link'].values.transpose)
#bodies is a sparse.csr_matrix with shape (7395, 20000)
bodies = sparse.hstack((bodies,X))
但是,此行给出错误 no supported conversion for types: (dtype('O'),)
。我不确定这是什么意思?我该如何绕过它?
谢谢。
最佳答案
这是 Saullo Castro 的评论作为答案:
x = np.arange(12).reshape(1,12) # ndarray
sparse.csr_matrix(x)
Out[14]: <1x12 sparse matrix of type '<type 'numpy.int32'>'
with 11 stored elements in Compressed Sparse Row format>
x.transpose # function, not ndarray
Out[15]: <function transpose>
X = sparse.csr_matrix(x.transpose)
TypeError: no supported conversion for types: (dtype('O'),)
错误发生在使用 hstack
之前,试图从函数而不是 ndarray 生成稀疏矩阵。错误是省略了 ()
。
# x.transpose() == x.T # ndarray
sparse.csr_matrix(x.transpose())
Out[17]: <12x1 sparse matrix of type '<type 'numpy.int32'>'
with 11 stored elements in Compressed Sparse Row format>
sparse.csr_matrix(x.T)
Out[18]: <12x1 sparse matrix of type '<type 'numpy.int32'>'
with 11 stored elements in Compressed Sparse Row format>
bodies = sparse.rand(12,3,format='csr',density=.1)
sparse.hstack((bodies,X))
Out[32]: <12x4 sparse matrix of type '<type 'numpy.float64'>'
with 14 stored elements in COOrdinate format>
csr_matrix
如果给定转置数组,则可以正常工作。
关于python - 稀疏 hstack 和奇怪的 dtype 转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18804040/