如何访问稀疏矩阵元素? [英] How to access sparse matrix elements?

查看:55
本文介绍了如何访问稀疏矩阵元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

type(A)
<class 'scipy.sparse.csc.csc_matrix'>
A.shape
(8529, 60877)
print A[0,:]
  (0, 25)   1.0
  (0, 7422) 1.0
  (0, 26062)    1.0
  (0, 31804)    1.0
  (0, 41602)    1.0
  (0, 43791)    1.0
print A[1,:]
  (0, 7044) 1.0
  (0, 31418)    1.0
  (0, 42341)    1.0
  (0, 47125)    1.0
  (0, 54376)    1.0
print A[:,0]
  #nothing returned

现在我不明白的是 A[1,:] 应该从第二行中选择元素,但我通过 print A[1,:].另外, print A[:,0] 应该返回第一列,但我没有打印任何内容.为什么?

Now what I don't understand is that A[1,:] should select elements from the 2nd row, yet I get elements from the 1st row via print A[1,:]. Also, print A[:,0] should return the first column but I get nothing printed. Why?

推荐答案

A[1,:] 本身就是一个形状为 (1, 60877) 的稀疏矩阵.这个就是你要打印的,而且只有一行,所以所有的行坐标都是0.

A[1,:] is itself a sparse matrix with shape (1, 60877). This is what you are printing, and it has only one row, so all the row coordinates are 0.

例如:

In [41]: a = csc_matrix([[1, 0, 0, 0], [0, 0, 10, 11], [0, 0, 0, 99]])

In [42]: a.todense()
Out[42]: 
matrix([[ 1,  0,  0,  0],
        [ 0,  0, 10, 11],
        [ 0,  0,  0, 99]], dtype=int64)

In [43]: print(a[1, :])
  (0, 2)    10
  (0, 3)    11

In [44]: print(a)
  (0, 0)    1
  (1, 2)    10
  (1, 3)    11
  (2, 3)    99

In [45]: print(a[1, :].toarray())
[[ 0  0 10 11]]

可以选择列,但是如果列中没有非零元素,用print输出时什么都不显示:

You can select columns, but if there are no nonzero elements in the column, nothing is displayed when it is output with print:

In [46]: a[:, 3].toarray()
Out[46]: 
array([[ 0],
       [11],
       [99]])

In [47]: print(a[:,3])
  (1, 0)    11
  (2, 0)    99

In [48]: a[:, 1].toarray()
Out[48]: 
array([[0],
       [0],
       [0]])

In [49]: print(a[:, 1])


In [50]:

最后一个 print 调用没有显示输出,因为 a[:, 1] 列没有非零元素.

The last print call shows no output because the column a[:, 1] has no nonzero elements.

这篇关于如何访问稀疏矩阵元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆