Home > OS >  In NumPy, what is the difference between [::-1][::-1] and [::-1, ::-1] 2d array indexing?
In NumPy, what is the difference between [::-1][::-1] and [::-1, ::-1] 2d array indexing?

Time:06-22

I wanted to reverse a 2d array and but got two different results while using [::-1][::-1] and [::-1, ::-1] indexing. Here is a sample below. I can't quite understand how it is differently interpreted.

values = [
    [5, 6, 5, 5, 8, 9, 9], 
    [9, 5, 1, 4, 5, 9, 7], 
    [3, 9, 6, 2, 1, 2, 3], 
    [1, 7, 6, 7, 1, 7, 5], 
    [2, 1, 3, 8, 7, 8, 8], 
    [2, 9, 3, 6, 4, 6, 4]
]
x = np.array(values)
reverse_2d_1 = x[::-1][::-1]
reverse_2d_2 = x[::-1, ::-1]
[[5 6 5 5 8 9 9]
 [9 5 1 4 5 9 7]
 [3 9 6 2 1 2 3]
 [1 7 6 7 1 7 5]
 [2 1 3 8 7 8 8]
 [2 9 3 6 4 6 4]]
[[4 6 4 6 3 9 2]
 [8 8 7 8 3 1 2]
 [5 7 1 7 6 7 1]
 [3 2 1 2 6 9 3]
 [7 9 5 4 1 5 9]
 [9 9 8 5 5 6 5]]

CodePudding user response:

In the first example, the two slices are resolved separately, because each slice is a separate operation. So the first [::-1] will flip the array vertically, and then the second [::-1] will flip it vertically again, leaving it as it started.

In the second example, the slices are resolved together, and each slice operates on the corresponding axis. So the first ::-1 will flip vertically, and the second ::-1 will flip horizontally.

If you find it easier to understand, you can also call np.flip(x, (0, 1)) to flip along the given axes.

  • Related