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
#6
(Feb-04-2022, 03:57 PM)deanhystad Wrote: If you start at the first row there is no previous row.

You can hang on to the previous row and print the previous row after you get the second row.
import pandas as pd
d = {'col1': ['A', 'B', 'C', 'D'], 'col2': [1, 2, 3, 4]}
df = pd.DataFrame(data=d)
 
prev = None    
for row in df.itertuples():
    print("Current index:",row)
    print("current col2 value:", getattr(row, 'col2'))
    if prev is not None:
        print("Previous col2 value:", getattr(prev,'col2'))
    prev = row
Or you can start printing the second row.
import pandas as pd
d = {'col1': ['A', 'B', 'C', 'D'], 'col2': [1, 2, 3, 4]}
df = pd.DataFrame(data=d)

rows = df.itertuples()
prev = next(rows)  # Gets first row
for row in rows:  # Will start at second row
    print("Current index:",row)
    print("current col2 value:", getattr(row, 'col2'))
    print("Previous col2 value:", getattr(prev,'col2'))
    prev = row

(Feb-04-2022, 03:57 PM)deanhystad Wrote: If you start at the first row there is no previous row.

You can hang on to the previous row and print the previous row after you get the second row.
import pandas as pd
d = {'col1': ['A', 'B', 'C', 'D'], 'col2': [1, 2, 3, 4]}
df = pd.DataFrame(data=d)
 
prev = None    
for row in df.itertuples():
    print("Current index:",row)
    print("current col2 value:", getattr(row, 'col2'))
    if prev is not None:
        print("Previous col2 value:", getattr(prev,'col2'))
    prev = row
Or you can start printing the second row.
import pandas as pd
d = {'col1': ['A', 'B', 'C', 'D'], 'col2': [1, 2, 3, 4]}
df = pd.DataFrame(data=d)

rows = df.itertuples()
prev = next(rows)  # Gets first row
for row in rows:  # Will start at second row
    print("Current index:",row)
    print("current col2 value:", getattr(row, 'col2'))
    print("Previous col2 value:", getattr(prev,'col2'))
    prev = row

I need to iterate over rows and need to access previous & current rows content on each iteration. Not just first row.
Reply


Messages In This Thread
RE: How to access previous row using itertuples - by SriRajesh - Feb-05-2022, 08:50 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] How to access previous row using itertuples newoptionz 1 735 Feb-28-2023, 04:43 PM
Last Post: deanhystad
  proper syntax for itertuples? ilcaa72 1 2,098 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