1

To reverse the last row is the first, we can write:

import numpy as np
a = np.arange(20) 
a = a.reshape(4,5) 
c = a[::-1,:]
print c 

c:
[[15 16 17 18 19]
 [10 11 12 13 14]
 [ 5  6  7  8  9]
 [ 0  1  2  3  4]]

But how does the slicing reverse use the last column last line be the first before?

I got just a line this way. But how do I arrive until the beginning of the matrix with this statement?

a[-1, -1::-1]

a:
[19 18 17 16 15]
Alex Riley
  • 169,130
  • 45
  • 262
  • 238
  • I'm not quite sure what you're asking - do you want to reverse *just* the last row of `a` and keep the other rows as they are? If you could post the array you're trying to end up with that would make everything clear. Thanks! – Alex Riley Mar 04 '15 at 16:13
  • [[19 18 17 16 15] [14 13 12 11 10] [9 8 7 6 5 ] [4 3 2 1 0]] keep the other rows, sorry! – richardson bruno Mar 04 '15 at 16:41
  • Ah OK - no problem, I've posted an answer below... – Alex Riley Mar 04 '15 at 16:48
  • @richardsonbruno don't forget you can accept an answer if you want – Saullo G. P. Castro Mar 05 '15 at 00:09
  • It looks like you are trying to flip the 2D array horizontally. If so, you could just use the "flip lr" functionality of numpy: https://docs.scipy.org/doc/numpy/reference/generated/numpy.fliplr.html – fgoettel Nov 27 '16 at 19:35

2 Answers2

4

You can reverse both the rows and columns of the 2D array by using the slice ::-1 in each axis:

>>> a[::-1, ::-1]
array([[19, 18, 17, 16, 15],
       [14, 13, 12, 11, 10],
       [ 9,  8,  7,  6,  5],
       [ 4,  3,  2,  1,  0]])
Alex Riley
  • 169,130
  • 45
  • 262
  • 238
1

A couple of other ways:

Reverse before making it 2d:

In [928]: np.arange(20)[::-1].reshape(4,5)
Out[928]: 
array([[19, 18, 17, 16, 15],
       [14, 13, 12, 11, 10],
       [ 9,  8,  7,  6,  5],
       [ 4,  3,  2,  1,  0]])

Reverse the values and copy them back in with flat.

In [929]: a=np.arange(20).reshape(4,5)
In [930]: a.flat[::-1]
Out[930]: 
array([19, 18, 17, 16, 15, 14, 13, 12, 11, 10,  9,  8,  7,  6,  5,  4,  3,
        2,  1,  0])
In [931]: a.flat[:]=a.flat[::-1]
In [932]: a
Out[932]: 
array([[19, 18, 17, 16, 15],
       [14, 13, 12, 11, 10],
       [ 9,  8,  7,  6,  5],
       [ 4,  3,  2,  1,  0]])
hpaulj
  • 221,503
  • 14
  • 230
  • 353