python - 稀疏 hstack 和奇怪的 dtype 转换错误

标签 python numpy scipy

在处理一些文本数据时,我试图将一个 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/

相关文章:

python - Scipy - 找到矩阵列空间的基础

python - 这个 Flask 代码中的 g 对象是什么?

python - 如何在 Pystray 中创建菜单和更新图标

python-3.x - scipy.ndimage 的替代方法旋转

python - 使用多处理填充 3D 数组

python - 多个索引的 Numpy 数组替换为不同的矩阵

python - 通过 Macports 安装 matplotlib basemap 后, basemap 的示例 python 代码未运行

python - Pyspark:如何删除仅几列的 dropduplicates 中的两个出现

python - 从 IMDbPy 结果中的片目中获取电影 ID

python - 使用 pandas 或 numpy 将数据拆分为 'classes'