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!
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.
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.
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.
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
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