Python Forum
How to access previous row using itertuples
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to access previous row using itertuples
#8
One way is to access rows by indices. Of course, there is still question about first row - whether it should be ignored or what?

import numpy as np
import pandas as pd

df = pd.DataFrame(np.arange(35).reshape(7, 5), columns=[*'abcde'])

for i in range(1, df.shape[0]):
    print("Current row", *df.iloc[i])
    print("Previous row",  *df.iloc[i-1])


Output:
Current row 5 6 7 8 9 Previous row 0 1 2 3 4 Current row 10 11 12 13 14 Previous row 5 6 7 8 9 Current row 15 16 17 18 19 Previous row 10 11 12 13 14 Current row 20 21 22 23 24 Previous row 15 16 17 18 19 Current row 25 26 27 28 29 Previous row 20 21 22 23 24 Current row 30 31 32 33 34 Previous row 25 26 27 28 29
I am not motivated enough to find out whether its faster than itertuples and getattr. I also believe that print is not the objective as I can't see any value of printing out 20K rows.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
RE: How to access previous row using itertuples - by perfringo - Feb-07-2022, 09:24 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] How to access previous row using itertuples newoptionz 1 733 Feb-28-2023, 04:43 PM
Last Post: deanhystad
  proper syntax for itertuples? ilcaa72 1 2,093 Jun-06-2019, 02:41 AM
Last Post: scidam

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020