Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through dataframe rows in reverse

Tags:

loops

pandas

I was trying to loop through dataframe rows in reverse order.

Based on row position rather than index name.

I though this code should work but its not.

for i, row in enumerate(df[::-1].iterrows()):  
    print (i)

As when I run it, it produces

0
1
2
3
4
5

rather than

5
4
3
2
1
0
like image 250
fred.schwartz Avatar asked Jul 03 '26 16:07

fred.schwartz


1 Answers

I you accept reindexing, you can also do

for i, row in enumerate(df.reindex().sort_index(ascending=False):  
    print (i)
like image 168
sslloo Avatar answered Jul 06 '26 05:07

sslloo