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?

Brandon
  • 1,029
  • 3
  • 11
  • 21

4 Answers4

27

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]

Community
  • 1
  • 1
pnv
  • 2,985
  • 5
  • 29
  • 36
5

It will be simpler to just do this:

df["Cherbourg"] = (df["Embarked"] == "C").astype('int)
EdChum
  • 376,765
  • 198
  • 813
  • 562
1
df["Cherbourg"] = df["Embarked"].apply(lambda x:1 if x == 'C' else 0)
j__carlson
  • 1,346
  • 3
  • 12
  • 20
raghu
  • 11
  • 1
  • 2
    This solution may work but please add some explanation to support this code solution. Also, please format the code inside backticks (`\``) – tshimkus Sep 11 '20 at 17:42
  • 1
    I doubt that this helps or even works at all. Would you like to add an explanation? – Yunnosch Sep 28 '20 at 16:32
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')
Georgi Popov
  • 43
  • 2
  • 9