说我有一定的映射:应用功能列在大熊猫数据帧有两个参数
mapping = {
'cat': 'purrfect',
'dog': 'too much work',
'fish': 'meh'
}
和dataframe
:
animal name description
0 cat sparkles NaN
1 dog rufus NaN
2 fish mr. blub NaN
我想用在description
列以编程方式填写animal
专栏和mapping
字典作为输入:
def describe_pet(animal,mapping):
return mapping[animal]
当我尝试用熊猫apply()
功能:
df['description'].apply(describe_pet,args=(df['animal'],mapping))
我得到以下错误:
TypeError: describe_pet() takes exactly 2 arguments (3 given)
好像使用apply()
是微不足道传递一个函数参数。我如何用两个参数来做到这一点?
这是非常优雅,当然最适合我的特殊情况。 Ophir Yoktan的回答适用于更一般的问题。 –