Python Forum
[split] How to access previous row using itertuples
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[split] How to access previous row using itertuples
#1
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?
Reply
#2
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/st...rrows.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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to access previous row using itertuples SriRajesh 7 8,080 Feb-07-2022, 09:24 AM
Last Post: perfringo
  proper syntax for itertuples? ilcaa72 1 2,088 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