Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge numpy arrays returned from loop

I have a loop that generates numpy arrays:

for x in range(0, 1000):
   myArray = myFunction(x)

The returned array is always one dimensional. I want to combine all the arrays into one array (also one dimensional.

I tried the following, but it failed

allArrays = []
for x in range(0, 1000):
   myArray = myFunction(x)
   allArrays += myArray

The error is ValueError: operands could not be broadcast together with shapes (0) (9095). How can I get that to work?

For instance these two arrays:

[ 234 342 234 5454 34 6]
[ 23 2 1 4 55 34]

Shall be merge into this array:

[ 234 342 234 5454 34 6 23 2 1 4 55 34 ]
like image 662
ustroetz Avatar asked Mar 26 '14 13:03

ustroetz


People also ask

How do I merge two NumPy arrays in Python?

Use numpy. concatenate() to merge the content of two or multiple arrays into a single array. This function takes several arguments along with the NumPy arrays to concatenate and returns a Numpy array ndarray. Note that this method also takes axis as another argument, when not specified it defaults to 0.

Can you combine NumPy arrays?

NumPy's concatenate function can be used to concatenate two arrays either row-wise or column-wise. Concatenate function can take two or more arrays of the same shape and by default it concatenates row-wise i.e. axis=0.


2 Answers

You probably mean

allArrays = np.array([])
for x in range(0, 1000):
    myArray = myFunction(x)
    allArrays = np.concatenate([allArrays, myArray])

A more concise approach (see wims answer) is to use a list comprehension,

allArrays = np.concatenate([myFunction(x) for x in range]) 
like image 193
jmetz Avatar answered Nov 15 '22 04:11

jmetz


You should know the shape of returned array. Suppose, myArray.shape = (2, 4) Then

allArrays = np.empty((0, 4))
for x in range(0, 1000):
    myArray = myFunction(x)
    allArrays = np.append(allArrays, myArray, axis = 0)
like image 24
Никита Черкес Avatar answered Nov 15 '22 04:11

Никита Черкес