python - Scipy:稀疏矩阵是否支持高级索引?

标签 python numpy scipy

没问题:

>>> t = np.array([[1,1,1,1,1],[2,2,2,2,2],[3,3,3,3,3],[4,4,4,4,4],[5,5,5,5,5]])
>>> x = np.arange(5).reshape((-1,1)); y = np.arange(5)
>>> print (t[[x]],t[[y]])

大问题:

>>> s = scipy.sparse.csr_matrix(t)
>>> print (s[[x]].toarray(),s[[y]].toarray())
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
:               :
:               :
ValueError: data, indices, and indptr should be rank 1

s.toarray()[[x]] 效果很好,但由于我的数组太大而破坏了我使用稀疏矩阵的全部目的。我已经检查了与一些稀疏矩阵关联的属性和方法,以查找任何引用高级索引的内容,但没有骰子。有什么想法吗?

最佳答案

稀疏矩阵的索引支持非常有限,可用的内容取决于矩阵的格式。

例如:

>>> a = scipy.sparse.rand(100,100,format='coo')
>>> a[2:5, 6:8]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'coo_matrix' object has no attribute '__getitem__'

但是

>>> a = scipy.sparse.rand(100,100,format='csc')
>>> a[2:5, 6:8]
<3x2 sparse matrix of type '<type 'numpy.float64'>'
    with 0 stored elements in Compressed Sparse Column format>

虽然

>>> a[2:5:2, 6:8:3]
Traceback (most recent call last):
...
ValueError: slicing with step != 1 not supported

还有

>>> a = scipy.sparse.rand(100,100,format='dok')
>>> a[2:5:2, 6:8:3]
Traceback (most recent call last):
...
NotImplementedError: fancy indexing supported over one axis only
>>> a[2:5:2,1]
<3x1 sparse matrix of type '<type 'numpy.float64'>'
    with 0 stored elements in Dictionary Of Keys format>

甚至

>>> a = scipy.sparse.rand(100,100,format='lil')
>>> a[2:5:2,1]
<2x1 sparse matrix of type '<type 'numpy.int32'>'
    with 0 stored elements in LInked List format>
C:\Python27\lib\site-packages\scipy\sparse\lil.py:230: SparseEfficiencyWarning: Indexing into a lil_matrix with multiple indices is slow. Pre-converting to CSC or CSR beforehand is more efficient.
  SparseEfficiencyWarning)
>>> a[2:5:2, 6:8:3]
<2x1 sparse matrix of type '<type 'numpy.int32'>'
    with 0 stored elements in LInked List format>

关于python - Scipy:稀疏矩阵是否支持高级索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14491548/

相关文章:

python - 使用助手服务在 watson studio 中创建 session 导致 SSL 错误

Python:对体素组件进行网格划分以计算表面积

python - 如何在 C 中编写一个函数,它将两个矩阵作为 numpy 数组的输入

python - 如何使用 Scipy 的 cKDTree 查询最近邻居,包括距离为零的邻居?

python - 使用涉及积分的方程提高 scipy.optimize.fsolve 的精度

python - scipy-cluster 定制生成的树状图

python - 在 python 中跟踪索引的正确方法是什么?

python - 设计 parking 系统问题输出时出错

python - 带有列表的列中按字符串的 pandas df 子集

arrays - Numpy 中的分块操作