0

I am iterating through the rows of a dataframe using iterrows:

for index, row in df.iterrows():
    pass

Given that the index here contains datetime objects, how can we easily access the row at the previous index (i-1) while being at level index (i) ?

Thanks

fqntom
  • 51
  • 6
  • Does this answer your question? [Python Pandas iterrows() with previous values](https://stackoverflow.com/questions/25473153/python-pandas-iterrows-with-previous-values) – Anurag Dabas May 15 '21 at 06:57
  • Yes I have seen this before asking my question... and I am not so sure how they convert an datetime to int using int(index)... – fqntom May 15 '21 at 07:00

1 Answers1

2

You can try below

row_ = None
for index, row in df.iterrows():
    # processing logic here (use row_ as prev row and "row" as current)
    row_ = row

row_ will be None if index is 0 else it will be previous row. This logic should work for any index type

Paras Gupta
  • 174
  • 4