Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map an if statement in Python

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?

like image 431
BrandonM Avatar asked Mar 25 '15 04:03

BrandonM


2 Answers

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]

like image 100
pnv Avatar answered Sep 24 '22 19:09

pnv


It will be simpler to just do this:

df["Cherbourg"] = (df["Embarked"] == "C").astype('int)
like image 23
EdChum Avatar answered Sep 20 '22 19:09

EdChum