将列添加到稀疏矩阵 [英] Add column to a sparse matrix

查看:105
本文介绍了将列添加到稀疏矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我执行以下代码时,我得到一个备用矩阵:

When I execute the following code I get a spares matrix:

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

我想向该稀疏矩阵添加另一列,因此输出为:

I want to add another column to this sparse matrix so the output is:

  (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的列.

Basically I want to add another column that has the values 7,7,7.

推荐答案

@Paul Panzer's链接中使用的sparse.hstack最简单.

The sparse.hstack used in @Paul Panzer's link is the simplest.

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.hstack is not complicated; it just calls bmat([blocks]).

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

sparse.bmat gets the coo attributes of all the blocks, joins them with the appropriate offself, and builds a new coo_matrix.

在这种情况下,它会加入

In this case it joins

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.

while changing the column numbers of the last to 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

这篇关于将列添加到稀疏矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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