Python Forum
[split] How to access previous row using itertuples - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: [split] How to access previous row using itertuples (/thread-39508.html)



[split] How to access previous row using itertuples - newoptionz - Feb-28-2023

I'm trying to update ta row's column based on the previous row's column's value.

Like the following

d = {'col1': ['A', 'B', 'C', 'D'], 'col2': [1, 2, 3, 4], 'col3': ['E', 'F', 'G', 'H']}
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)
    setattr(row, 'col3') = getattr(prev,'col1')
    prev = row
This throws the error, 'SyntaxError: cannot assign to function call'. Guess I will have to use iloc or loc?


RE: [split] How to access previous row using itertuples - deanhystad - Feb-28-2023

Post entire error message including trace.

This is a function call.
setattr(row, 'col3')
You cannot assign a value to a function call. Something like this is valid Python.
setattr(row, 'col3', getattr(prev,'col1'))
But it is not valid for a pandas dataframe "row". Even if such a call was allowed, it wouldn't work.

From the pandas documentation

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html
Quote:You should never modify something you are iterating over. This is not guaranteed to work in all cases. Depending on the data types, the iterator returns a copy and not a view, and writing to it will have no effect.

So you shouldn't be doing what you are trying to do. What are your trying to achieve? I assume this is just example code to demonstrate the setattr error.

With pandas, for loops usually mean you are doing something wrong.