Here is my code:
import pandas as pd
data = pd.DataFrame({\'Odd\':[1,3,5,6,7,9], \'Even\':[0,2,4,6,8,10]})
for i in reversed(data):
print(data[\'Odd\']
This works:
for i,r in data[::-1].iterrows():
print(r['Odd'], r['Even'])
You can reverse the rows in an even simpler way:
df[::-1]
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 )
The right way to do this is:
data = data.sort_index(ascending=False)
This approach has the benefits of (1) being a single line, (2) not requiring a utility function, and most importantly (3) not actually changing any of the data in the dataframe.
None of the existing answers resets the index after reversing the dataframe.
For this, do the following:
data[::-1].reset_index()
Here's a utility function that also removes the old index column, as per @Tim's comment:
def reset_my_index(df):
res = df[::-1].reset_index(drop=True)
return(res)
Simply pass your dataframe into the function
The simplest solution might be
data = data[::-1]