向稀疏矩阵添加列

14

当我执行以下代码时,会得到一个稀疏矩阵:

import numpy as np
from scipy.sparse import csr_matrix

row = np.array([0, 0, 1, 2, 2, 2])
col = np.array([0, 2, 2, 0, 1, 2])
data = np.array([1, 2, 3, 4, 5, 6])
sp = csr_matrix((data, (row, col)), shape=(3, 3))
print(sp)

  (0, 0)        1
  (0, 2)        2
  (1, 2)        3
  (2, 0)        4
  (2, 1)        5
  (2, 2)        6
我想要向这个稀疏矩阵添加另一列,以便输出结果为:
  (0, 0)        1
  (0, 2)        2
  (0, 3)        7
  (1, 2)        3
  (1, 3)        7
  (2, 0)        4
  (2, 1)        5
  (2, 2)        6
  (2, 3)        6

基本上,我想添加另一列表格,其值为7,7,7。


3
请点击这里查看。该页面讨论了如何在Python中使用Scipy和Numpy连接稀疏矩阵。 - Paul Panzer
1个回答

21

sparse.hstack@Paul Panzer's的链接中使用,是最简单的方法。

In [760]: sparse.hstack((sp,np.array([7,7,7])[:,None])).A
Out[760]: 
array([[1, 0, 2, 7],
       [0, 0, 3, 7],
       [4, 5, 6, 7]], dtype=int32)

sparse.hstack 并不复杂,它只是调用 bmat([blocks])

sparse.bmat 获取所有块的 coo 属性,将它们与适当的偏移量连接起来,并构建一个新的 coo_matrix

在这种情况下,它连接了:

In [771]: print(sp)
  (0, 0)    1
  (0, 2)    2
  (1, 2)    3
  (2, 0)    4
  (2, 1)    5
  (2, 2)    6
In [772]: print(sparse.coo_matrix(np.array([7,7,7])[:,None]))
  (0, 0)    7
  (1, 0)    7
  (2, 0)    7

将最后一列的列数更改为3

In [761]: print(sparse.hstack((sp,np.array([7,7,7])[:,None])))
  (0, 0)    1
  (0, 2)    2
  (1, 2)    3
  (2, 0)    4
  (2, 1)    5
  (2, 2)    6
  (0, 3)    7
  (1, 3)    7
  (2, 3)    7

.A 是在做什么? - CKM
@chandresh .A 返回自身作为ndarray对象 - Vadim Shkaberda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接