1

I'm unable to bring my head around the syntax used for reversing all rows vs reversing all columns in Pandas.

1. Reversing all rows : df.iloc[::-1]
2. Reversing all columns : df.iloc[:,::-1]

On a related note, what would be the way to reverse both rows and columns?

Kshitij Kohli
  • 4,055
  • 4
  • 19
  • 27

1 Answers1

3

On a related note, what would be the way to reverse both rows and columns?

df.iloc[::-1, ::-1]

I think for explain slicing is best check how working it in lists, here is used exactly same principe:

a[::-1]    # all items in the array, reversed
a[1::-1]   # the first two items, reversed
a[:-3:-1]  # the last two items, reversed
a[-3::-1]  # everything except the last two items, reversed

Pandas rows:

df.iloc[::-1]    # all items in the array, reversed
df.iloc[1::-1]   # the first two items, reversed
df.iloc[:-3:-1]  # the last two items, reversed
df.iloc[-3::-1]  # everything except the last two items, reversed

Btw, it is same like slice rows, get all columns with :, but obviously omited, because working same:

df.iloc[::-1]
df.iloc[::-1, :]
....

Pandas columns - first : means get all rows, then slice columns

df.iloc[:, ::-1]    # all items in the array, reversed
df.iloc[:, 1::-1]   # the first two items, reversed
df.iloc[:, :-3:-1]  # the last two items, reversed
df.iloc[:, -3::-1]  # everything except the last two items, reversed
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Hey, works perfectly. Can you explain me the format as well. What my understanding was a simple : means to select everything from start to end. In case we want to specific the skip level as well ( -1 in this case ), we add another colon, is it? – Kshitij Kohli Apr 04 '20 at 10:49