check if last row in pandas df.iterrows()

Viewed 14686

How can I check last row in Python pandas df.itterows() during its iteration?

My code :

for index, row in df.iterrows():
...     # I want to check last row in df iterrows(). somelike row[0].tail(1)
2 Answers

The pandas.DataFrame class has a subscriptable index attribute. So one can check the index of the row when iterating over the row using iterrows() against the last value of the df.index attribute like so:

for idx,row in df.iterrows():
    if idx == df.index[-1]:
        print('This row is last')
Related