使用 Python 字典 get 方法,默认值为 lambda

Using Python dictionary get method with default value as lambda

在以下情况下如何设置字典映射的默认值?没有默认值,我收到 'None' 作为响应,但我更喜欢 'Others' 作为默认 return 值。

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

我知道 Python 字典 get 方法接受默认值作为第二个参数。

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

将get方法作为参数传递给其他函数时,如何设置第二个参数?

你只需要这样做,

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

输出-

GenderCode GenderDesc
0 M Male
1 F Female
2 R Others

几个选项。

fillna映射后:

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

或者,使用 lambda 映射:

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

或者,使用 defaultdict:

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

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

或者,使用 Series.applyarg 参数将参数传递给函数。

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

输出:

  GenderCode GenderDesc
0          M       Male
1          F     Female
2          R      Other