Home > database >  Concatinate and reshape 2 numpy array with different with dimensions on high dimensions
Concatinate and reshape 2 numpy array with different with dimensions on high dimensions

Time:12-26

I have a 2 numpy arrays like the following

a = np.random.rand(30,6,5,4)
b = np.random.rand(6,5,4,3)

I want to cocatinate these arrays in a way that it has the shape (33, 6, 5, 4). I can do this by iterating through the 4th dimension of the b array and concatenating one by one but it doesn't seem very efficient. Is it possible to do this in a more "Python" way?

CodePudding user response:

You could always flatten any two arrays, concatenate, and then reshape to the dimensions you want. In general, the shape of an array does nothing to the memory that is used to hold the array. The shape simply specifies how python accesses the values.

Hence .flatten() is a zero cost function and doesn't move any memory values around. It is equivalent to just setting the shape value:

A = np.array([[1,2],[3,4]])
A.shape = (4,)

If the values in your flatten'd array are not in the order you wanted, you may need to run transpose to move the values to the order you want.

CodePudding user response:

In [390]: a = np.random.rand(30,6,5,4)
     ...: b = np.random.rand(6,5,4,3)

use transpose to get b into a compatible shape:

In [392]: b1=np.transpose(b,(3,0,1,2))
In [393]: b1.shape
Out[393]: (3, 6, 5, 4)
In [394]: c = np.concatenate((a,b1),axis=0)
In [395]: c.shape
Out[395]: (33, 6, 5, 4)

You don't give details on the iterative approach, but this is only one that makes sense to me:

In [398]: alist = [a]
     ...: for i in range(3):
     ...:     alist.append(b[None,...,i])
     ...: 
In [399]: np.concatenate(alist, 0).shape
Out[399]: (33, 6, 5, 4)
  • Related