Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scipy append all rows of one sparse matrix to another

I have a numpy matrix and want to append another matrix to that.

The two matrices have the shapes:

m1.shape = (2777, 5902)  m2.shape = (695, 5902)

I want to append m2 to m1 so that the new matrix is of shape:

m_new.shape = (3472, 5902)

When I use numpy.append or numpy.concatenate I just get a new array with the two matrix in it and the shape (2,1).

Any one of you have an Idea how to get one big matrix out of the two?

Additional info: both are sparse matrices.

EDIT: m1 looks like

(0, 1660)   0.444122811195
(0, 3562)   0.260868771714
(0, 4743)   0.288149437574
(0, 4985)   0.514889706991
(0, 5215)   0.272163636657
(0, 5721)   0.559006134727
(1, 555)    0.0992498400527
(1, 770)    0.133145289523
(1, 790)    0.0939044698233
(1, 1097)   0.259867567986
(1, 1285)   0.188836288168
(1, 1366)   0.24707459927
(1, 1499)   0.237997843516
(1, 1559)   0.120069347224
(1, 1701)   0.17660176488
(1, 1926)   0.185678520634
(1, 2177)   0.163066377369
(1, 2641)   0.079958199952
(1, 2937)   0.259867567986
(1, 3551)   0.198471489351
(1, 3562)   0.0926197593026
(1, 3593)   0.100537828805
(1, 4122)   0.198471489351
(1, 4538)   0.57162654484
(1, 4827)   0.105808609537

m2 looks like:

(0, 327)    0.0770581299315
  (0, 966)  0.309858753157
  (0, 1231) 0.286870892505
  (0, 1384) 0.281385698712
  (0, 1817) 0.204495931592
  (0, 2284) 0.182420951496
  (0, 2414) 0.114591086901
  (0, 2490) 0.261442040482
  (0, 3122) 0.321676138471
  (0, 3151) 0.286870892505
  (0, 4031) 0.172251612658
  (0, 5149) 0.25839783806
  (0, 5215) 0.125806303262
  (0, 5225) 0.336280781816
  (0, 5231) 0.135930403721
  (0, 5294) 0.145049459537
  (0, 5794) 0.20145172917
  (0, 5821) 0.224439589822
  (1, 327)  0.191031948626
  (1, 1171) 0.62081265022

Type of the matrices is:

<class 'scipy.sparse.csr.csr_matrix'> <class 'scipy.sparse.csr.csr_matrix'>

SOLVED:

m_new = scipy.sparse.vstack((m1, m2))

did the trick

Thanks for your help.

like image 500
d.a.d.a Avatar asked Nov 26 '22 18:11

d.a.d.a


1 Answers

You can use numpy.vstack in your case (or numpy.hstack, when matrices shapes are (x,y) and (x,z))

Example:

a = np.zeros((3,7))
b = np.zeros((46,7))
c = np.vstack((a,b))
print c.shape
#(49,7)
like image 116
greenwolf Avatar answered Dec 08 '22 14:12

greenwolf