Home > Blockchain >  Using Python dictionary get method with default value as lambda
Using Python dictionary get method with default value as lambda

Time:06-05

How do I set default value for dictionary mapping in the following case? Without default value, I receive 'None' as response, but I prefer 'Others' as default return value.

>>> df = pd.DataFrame({ 'GenderCode' : ['M', 'F', 'R']})
>>> df
  GenderCode
0          M
1          F
2          R
>>> mapping = { 'M' : 'Male', 'F' : 'Female' }
>>> df['GenderDesc'] = df['GenderCode'].apply(mapping.get)
>>> df
  GenderCode GenderDesc
0          M       Male
1          F     Female
2          R       None

I know that Python dictionary get method accepts default value as second parameter.

>>> mapping.get('R', 'Others')
'Others'

How do I set the second parameter when passing the get method as parameter to other function?

CodePudding user response:

You just have to do this,

df['GenderDesc'] = df['GenderCode'].apply(lambda key:mapping.get(key, "Others"))

Output -

GenderCode GenderDesc
0 M Male
1 F Female
2 R Others

CodePudding user response:

Several options.

fillna after mapping:

df['GenderDesc'] = df['GenderCode'].map(mapping).fillna('Other')

Or, map with a lambda:

df['GenderDesc'] = df['GenderCode'].map(lambda x: mapping.get(x, 'Others'))

Or, use a defaultdict:

from collections import defaultdict 
mapping = defaultdict(lambda:'Other', mapping)

df['GenderDesc'] = df['GenderCode'].map(mapping)

Or, use Series.apply's arg parameter to pass arguments to the function.

df['GenderCode'].apply(mapping.get, args=('Others', ))

Output:

  GenderCode GenderDesc
0          M       Male
1          F     Female
2          R      Other
  • Related