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

2
  • Does this answer your question? Python Pandas iterrows() with previous values Commented May 15, 2021 at 6: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)... Commented May 15, 2021 at 7:00

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

was a type. fixed it :P. Other simple way is using row_ initialized as None out side loop and after using it, you can set row_ as row at the end of the loop
Well in fact df.iloc[index-1] doesnt work at my index is a datetime and not an integer
Editted that, it should work for any index

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.