Amani
Amani

Reputation: 18123

Error with lambda function in pandas

I have a data frame sp with a column named Status. The values in the Status column are either 'Done' or 'Waiting'. I need to change the values of the Status column using a lambda function, where a status of 'Done' is changed to 'A' and a status of 'Waiting' is changed to 'N'. This is how I tried to do it:

sp['Status'] = sp['Status'].apply(lambda x: x='A' if x=='Done' else x='N')

I then get the following error message:

sp['Status'] = sp['Status'].apply(lambda x: x='A' if x=='Done' else x='N')
                                                                     ^
SyntaxError: invalid syntax

Where am I doing wrong?

Upvotes: 0

Views: 2146

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121714

You can't use assignment (a statement) inside a lambda (which only takes expressions).

The lambda should instead just return the new value:

sp['Status'] = sp['Status'].apply(lambda x: 'A' if x == 'Alive' else 'N')

The result of the expression in a lambda is always the return value.

Note that you just use Series.map() here instead:

sp['Status'] = sp['Status'].map({'Alive': 'A', 'Waiting': 'N'})

Upvotes: 2

Zah
Zah

Reputation: 6804

You have to read the lambda syntax as if there was a return in front. And you cannot make assignments in the lambda body:

sp['Status'] = sp['Status'].apply(lambda x: 'A' if x=='Done' else 'N')

Upvotes: 1

Related Questions