Eric Escobar
Eric Escobar

Reputation: 243

Combining rows numpy to one single array

I have a while statement that produces an array in numpy

while(i<int(sp)): 
   body=(np.bincount(un[i].ravel().astype('int'), weights=step_periods[i].ravel())) 
   print(body) 
   i=i+1

each iteration produces an array of like the following:

1st    [  0.   0.   0.  30.]

2nd    [  0.   0.  21.  18.  15.]

3rd    [  0.  24.  27.   0.   3.]

My first issue is that if the first array has "0" as the last value, it will leave it out of the array. Is there a way to convert it from:

[  0.   0.   0.  30.]

to:

[  0.   0.   0.  30.  0.]

From there I would like to simply append each array to a master array so that the final output is something similar to:

    [[  0.   0.   0.  30.  0.0],

    [  0.   0.  21.  18.  15.],

   [  0.  24.  27.   0.   3.]]

I've looked into appending and vstack, but can't get it to work in a "while" statement, or possibly because they aren't all the same size due to the ending "0" being ommited!

Thanks!

Upvotes: 0

Views: 160

Answers (1)

mgilson
mgilson

Reputation: 310029

One solution -- if you can guarantee that the length of body is always going to be less than (or equal to) 5, you can pre-allocate the array:

import numpy as np
my_array = np.zeros((int(sp)-i,5),dtype=int)
for ii in range(i,int(sp)):
    body=(np.bincount(un[i].ravel().astype('int'), weights=step_periods[i].ravel())) 
    my_array[ii,:len(body)]=body 

You could even add a check to see if body got too wide and create a new array, assigning the old portion into it ... But at that point, maybe a stacking operation is what is needed.

Upvotes: 1

Related Questions