Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy vstack inside for loop [duplicate]

I want to make an numpy array out of a list of numpy array. Let's say we have three array a, b, c (Well, actually I have 2000 arrays in a list in my code but for simplicity, I just extracted three of them)

a
Out[155]: 
array([-3.6673906, -0.6282566,  5.753459 , -3.4316962,  1.1095421,
       -3.857554 ,  2.1034663,  1.1664252,  5.030331 ,  2.8712769,
       -6.43062  , -4.375715 , -1.6669037,  3.340822 ,  0.520241 ,
        1.4352009, -1.7027975, -2.5952163, -1.0833957,  1.2216603],
      dtype=float32)
b
Out[156]: 
array([-3.0786738 , -0.4769052 ,  3.9245896 , -7.2456822 , -1.3267522 ,
       -0.71329254,  0.41840628, -0.90246826,  3.9599216 ,  0.91597205,
       -2.7932754 , -2.9929597 , -1.729125  , -2.4315472 , -6.188235  ,
        6.450362  , -1.1097518 , -0.3890484 , -3.6735342 , -0.20976427],
      dtype=float32)
c
Out[157]: 
array([ 1.2807868 ,  2.9086506 , -0.90828913, -5.387167  ,  2.5136113 ,
       -6.1260514 , -4.2776265 ,  2.1921122 ,  1.8431641 , -2.623109  ,
        0.2086102 , -3.3588243 , -1.7712283 ,  3.4094403 , -3.6030903 ,
        1.8072847 ,  4.6180625 , -1.6826918 , -1.4339283 ,  0.39811078],
      dtype=float32)

I want to have a function func(list_of_arrays) which returns one array just stacking elements from the list. like this:

array([[-3.6673906 , -0.6282566 ,  5.753459  , -3.4316962 ,  1.1095421 ,
        -3.857554  ,  2.1034663 ,  1.1664252 ,  5.030331  ,  2.8712769 ,
        -6.43062   , -4.375715  , -1.6669037 ,  3.340822  ,  0.520241  ,
         1.4352009 , -1.7027975 , -2.5952163 , -1.0833957 ,  1.2216603 ],
       [-3.0786738 , -0.4769052 ,  3.9245896 , -7.2456822 , -1.3267522 ,
        -0.71329254,  0.41840628, -0.90246826,  3.9599216 ,  0.91597205,
        -2.7932754 , -2.9929597 , -1.729125  , -2.4315472 , -6.188235  ,
         6.450362  , -1.1097518 , -0.3890484 , -3.6735342 , -0.20976427],
       [ 1.2807868 ,  2.9086506 , -0.90828913, -5.387167  ,  2.5136113 ,
        -6.1260514 , -4.2776265 ,  2.1921122 ,  1.8431641 , -2.623109  ,
         0.2086102 , -3.3588243 , -1.7712283 ,  3.4094403 , -3.6030903 ,
         1.8072847 ,  4.6180625 , -1.6826918 , -1.4339283 ,  0.39811078]],
      dtype=float32)

I could do this 3 arrays with following commands.

y1 = np.vstack((a,b))
y2 = np.vstack((y1,c))

However, I cannot do this with list of 2000 arrays. I wish numpy was as easy as list, so I can just append everything in an empty list. Can someone please give me some idea?

like image 797
Sujoung Baeck Avatar asked Aug 31 '18 15:08

Sujoung Baeck


1 Answers

vstack doesn't just accept two arrays. It accepts an iterable of rows to stack. You can directly do

np.vstack([a, b, c, d, e])

or, generally

np.vstack(my_arrays)
like image 55
blue_note Avatar answered Nov 12 '22 12:11

blue_note