scipy.sparse.hstack vstack

首先格式是符合 coo_matrix 才能使用sparse进行拼接。

hstack :
将矩阵按照列进行拼接

from scipy.sparse import coo_matrix, hstack,vstack
A = coo_matrix([[1, 2], [3, 4]])
print(A)
B = coo_matrix([[5,7], [6,8]])
print(hstack([A,B]))
print(hstack([A,B]).toarray())

输出:

 (0, 0) 1
  (0, 1)    2
  (1, 0)    3
  (1, 1)    4
  (0, 0)    1
  (0, 1)    2
  (1, 0)    3
  (1, 1)    4
  (0, 2)    5
  (0, 3)    7
  (1, 2)    6
  (1, 3)    8
[[1 2 5 7]
 [3 4 6 8]]

vstack
将矩阵按照行进行拼接,对应的列数必须相等

from scipy.sparse import coo_matrix, hstack,vstack
A = coo_matrix([[1, 2], [2, 4]])
print(A)
B = coo_matrix([[5,7], [6,8]])
print(vstack([A,B]))
print(vstack([A,B]).toarray())

输出:

(0, 0)  1
  (0, 1)    2
  (1, 0)    2
  (1, 1)    4
  (0, 0)    1
  (0, 1)    2
  (1, 0)    2
  (1, 1)    4
  (2, 0)    5
  (2, 1)    7
  (3, 0)    6
  (3, 1)    8
[[1 2]
 [2 4]
 [5 7]
 [6 8]]

猜你喜欢

转载自blog.csdn.net/th_num/article/details/80044197