25

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!

3 Answers 3

42

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.

Sign up to request clarification or add additional context in comments.

1 Comment

a[..., 3::-1] is still OK, but now a surprise: a[..., 3:-1:-1] results in: array([], shape=(2, 3, 0), dtype=int64). It is numpy 1.7.1. Unpleasant, right?
1

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

Comments

0

You can do this easily with numpy.flip():

import numpy as np
a = 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]]])
print(np.flip(a, axis=2))

Which gives:

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]]])

as required. The input array is three dimensional due to the extra square brackets. So, flipping along axis=2, means flipping the 3rd axis (since the count starts at 0).

Note that this returns a view, not a copy (see docs).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.