10

I'm trying to map the following function over a pandas dataframe (basically a list) in python 2.7:

df["Cherbourg"] = df["Embarked"].map(lambda x: if (x == "C") 1 else 0)

But python errors saying using a lambda function like this is a syntax error. Is there some way to map an if statement like this in python?

4 Answers 4

29

Try

lambda x: 1 if x == "C" else 0

possible duplicate of Is there a way to perform "if" in python's lambda

Example :

map(lambda x: True if x % 2 == 0 else False, range(1, 11))

result will be - [False, True, False, True, False, True, False, True, False, True]

Sign up to request clarification or add additional context in comments.

Comments

5

It will be simpler to just do this:

df["Cherbourg"] = (df["Embarked"] == "C").astype('int)

Comments

1
df["Cherbourg"] = df["Embarked"].apply(lambda x:1 if x == 'C' else 0)

2 Comments

This solution may work but please add some explanation to support this code solution. Also, please format the code inside backticks (`)
I doubt that this helps or even works at all. Would you like to add an explanation?
0

A more readable approach:

def mapping(row):
    if row.Embarked == 'C':
        row.Cherbourg = 1
    else:
        row.Cherbourg = 0
return row
    
df.apply(mapping, axis='columns')

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.