Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy reverse multidimensional array

Tags:

What is the simplest way in numpy to reverse the most inner values of an array like this:

array([[[1, 1, 1, 2],     [2, 2, 2, 3],     [3, 3, 3, 4]],     [[1, 1, 1, 2],     [2, 2, 2, 3],     [3, 3, 3, 4]]]) 

so that I get the following result:

array([[[2, 1, 1, 1],     [3, 2, 2, 2],     [4, 3, 3, 3]],     [[2, 1, 1, 1],     [3, 2, 2, 2],     [4, 3, 3, 3]]]) 

Thank you very much!

like image 279
xyz-123 Avatar asked Sep 14 '11 12:09

xyz-123


People also ask

How do I reverse a NumPy 2D array?

For each of the inner array you can use fliplr. It flips the entries in each row in the left/right direction. Columns are preserved, but appear in a different order than before. Make sure your input array for fliplr function must be at least 2-D.

How do I reverse the order of a NumPy array?

NumPy: flip() function The flip() function is used to reverse the order of elements in an array along the given axis. The shape of the array is preserved, but the elements are reordered.


2 Answers

How about:

import numpy as np a = np.array([[[10, 1, 1, 2],                [2, 2, 2, 3],                [3, 3, 3, 4]],               [[1, 1, 1, 2],                [2, 2, 2, 3],                [3, 3, 3, 4]]]) 

and the reverse along the last dimension is:

b = a[:,:,::-1] 

or

b = a[...,::-1] 

although I like the later less since the first two dimensions are implicit and it is more difficult to see what is going on.

like image 60
JoshAdel Avatar answered Sep 19 '22 13:09

JoshAdel


For each of the inner array you can use fliplr. It flips the entries in each row in the left/right direction. Columns are preserved, but appear in a different order than before.

Sample usage:

import numpy as np initial_array = np.array([[[1, 1, 1, 2],                           [2, 2, 2, 3],                           [3, 3, 3, 4]],                          [[1, 1, 1, 2],                           [2, 2, 2, 3],                           [3, 3, 3, 4]]]) index=0 initial_shape = initial_array.shape reversed=np.empty(shape=initial_shape) for inner_array in initial_array:     reversed[index] = np.fliplr(inner_array)     index += 1 

printing reversed

Output:

array([[[2, 1, 1, 1],         [3, 2, 2, 2],         [4, 3, 3, 3]],        [[2, 1, 1, 1],         [3, 2, 2, 2],         [4, 3, 3, 3]]]) 

Make sure your input array for fliplr function must be at least 2-D.

Moreover if you want to flip array in the up/down direction. You can also use flipud

like image 26
sakhala Avatar answered Sep 17 '22 13:09

sakhala