Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping the dimensions of a numpy array

I would like to do the following:

for i in dimension1:   for j in dimension2:     for k in dimension3:       for l in dimension4:         B[k,l,i,j] = A[i,j,k,l] 

without the use of loops. In the end both A and B contain the same information but indexed differently.

I must point out that the dimension 1,2,3 and 4 can be the same or different. So a numpy.reshape() seems difficult.

like image 846
sponce Avatar asked May 29 '14 21:05

sponce


People also ask

How do you change the dimension of a NumPy array?

The shape of the array can also be changed using the resize() method. If the specified dimension is larger than the actual array, The extra spaces in the new array will be filled with repeated copies of the original array.

How do you reverse the axis of a NumPy array?

The numpy. flip() function reverses the order of array elements along the specified axis, preserving the shape of the array. Parameters : array : [array_like]Array to be input axis : [integer]axis along which array is reversed.


1 Answers

The canonical way of doing this in numpy would be to use np.transpose's optional permutation argument. In your case, to go from ijkl to klij, the permutation is (2, 3, 0, 1), e.g.:

In [16]: a = np.empty((2, 3, 4, 5))  In [17]: b = np.transpose(a, (2, 3, 0, 1))  In [18]: b.shape Out[18]: (4, 5, 2, 3) 
like image 93
Jaime Avatar answered Sep 19 '22 23:09

Jaime