Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multidimensional numpy array -- reverse along a given axis

Let's say I have a multidimensional array with a shape that I don't know until runtime.

How can I reverse it along a given axis k, also not known until runtime?

The notation somearray[:,:,::-1,:,:] relies on static dimension references, as in this other SO question, so I can't use it here.

like image 893
Jason S Avatar asked Jun 29 '13 00:06

Jason S


People also ask

How do you reverse a multi dimensional array in Python?

Use numpy.The numpy. fliplr() function is used to reverse the order of elements for a 2-D array. This flip array entry in each row in the left-right direction. columns are preserved but appear in a different order than before.

How do I reverse the columns of a 2D array in NumPy?

An array object in NumPy is called ndarray, which is created using the array() function. To reverse column order in a matrix, we make use of the numpy. fliplr() method. The method flips the entries in each row in the left/right direction.

How do you reverse the order of elements along rows?

B = flip( A , dim ) reverses the order of the elements in A along dimension dim . For example, if A is a matrix, then flip(A,1) reverses the elements in each column, and flip(A,2) reverses the elements in each row.


1 Answers

You can either construct a tuple of slice objects such as @ali_m suggests, or do something like this:

reversed_arr = np.swapaxes(np.swapaxes(arr, 0, k)[::-1], 0, k)

This places the desired axis at the front of the shape tuple, then reverses that first axis, and then returns it to its original position.

Some people think this approach lacks readability, but I disagree.

like image 176
Jaime Avatar answered Sep 30 '22 19:09

Jaime