Feb-05-2022, 08:50 AM
(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 = rowOr 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 = rowOr 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.