0

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?

1
  • Your error message doesn't match your code. Please do post the actual error so as not to confuse answerers. Commented May 15, 2016 at 12:25

2 Answers 2

2

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'})
Sign up to request clarification or add additional context in comments.

Comments

1

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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.