Home > Blockchain >  How to stack numpy array along an axis
How to stack numpy array along an axis

Time:06-28

I have two numpy arrays, one with shape let's say (10, 5, 200), and another one with the shape (1, 200), how can I stack them so I get as a result an array of dimensions (10, 6, 200)? Basically by stacking it to each 2-d array iterating along the first dimension

a = np.random.random((10, 5, 200))
b = np.zeros((1, 200))

I'v tried with hstack and vstack but I get an error in incorrect number of axis

CodePudding user response:

Let's say:

a = np.random.random((10, 5, 200))
b = np.zeros((1, 200))

Let's look at the volume (number of elements) of each array:

The volume of a is 10*5*200 = 10000. The volume of an array with (10,6,200) is 10*5*200=1200.

That is you want to create an array that has 2000 more elements. However, the volume of b is 1*200 = 200.

This means a and b can't be stacked.

CodePudding user response:

As hpaulj mentioned in the comments, one way is to define an numpy array and then fill it:

result = np.empty((a.shape[0], a.shape[1]   b.shape[0], a.shape[2]))
result[:, :a.shape[1], :] = a
result[:, a.shape[1]:, :] = b
  • Related