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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With