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 ]
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.
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.
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])
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With