Reputation: 53
I'm trying to do what this person is doing numpy: extending arrays along a new axis? but I don't want to repeat the same array in the new dimension. I'm generating a new 2D array and want to append it along a 3rd dimension
I've tried using np.stack((a,b), axis=2) but the arrays need to be the same shape. So after it stacks the first two arrays, the shapes on the second iteration are (256, 256, 2) and (256, 256) and I get ValueError: all input arrays must have the same shape
a = something #a has shape (256, 256)
for i in np.arange(0,10):
#calculate b and it also has shape (256,256)
a = np.stack((a,b), axis=2)
print(a.shape) #should give (256, 256, 10)
Upvotes: 3
Views: 3561
Reputation: 591
You can do this efficiently using np.concatenate and the magic of np.newaxis
import numpy as np
# generating a list of arrays.
arr_list = [np.random.rand(256, 256)]*512 # array with shape (256, 256)
# run a list comprehension inside np.concatenate.
# use np.newaxis along the first dimension. Numpy can work along the first axis way faster (~10x faster in this case).
c = np.concatenate([arr[np.newaxis, ...] for arr in arr_list])
# c is now of shape (512, 256, 256)
Upvotes: 0
Reputation: 45
You can also do this by storing the arrays in a list and using np.stack
. Perhaps not as efficient, but I find it easier to read.
import numpy as np
a = np.random.rand(256, 256) # array with shape (256, 256)
c = [a] # put initial array into a list
for i in np.arange(10):
b = np.random.rand(256, 256) # b is also array with shape (256, 256)
c.append(b) # append each new array to the list
# convert the list of arrays to 3D array
final = np.stack(c, axis=2) # axis argument specifies which axis to stack along
Upvotes: 3
Reputation: 21
You want to concatenate your arrays but along a new third dimension. To get the array dimensions to agree you can make use of None when indexing them. To follow your example above, this would look like:
import numpy as np
a = np.random.rand(256, 256) # something with shape (256, 256)
c = a[ :, :, None] # start out by copying a into c but add in an extra dimension using None
for i in np.arange(10):
b = np.random.rand(256, 256) # b is also something with shape (256, 256)
c = np.concatenate((c, b[ :, :, None]), axis=2) # concatenate it to c, again using None to add in the extra dimension to b, and joining along the new axis.
c.shape # will be (256,256,11) for each of the ten iterations plus the initial copying of a into c.
Upvotes: 1