Right way to reverse a pandas DataFrame?
data.reindex(index=data.index[::-1])
or simply:
data.iloc[::-1]
will reverse your data frame, if you want to have a for
loop which goes from down to up you may do:
for idx in reversed(data.index):
print(idx, data.loc[idx, 'Even'], data.loc[idx, 'Odd'])
or
for idx in reversed(data.index):
print(idx, data.Even[idx], data.Odd[idx])
You are getting an error because reversed
first calls data.__len__()
which returns 6. Then it tries to call data[j - 1]
for j
in range(6, 0, -1)
, and the first call would be data[5]
; but in pandas dataframe data[5]
means column 5, and there is no column 5 so it will throw an exception. ( see docs )
You can reverse the rows in an even simpler way:
df[::-1]