假设我有一个特定的映射:
mapping = {
'cat': 'purrfect',
'dog': 'too much work',
'fish': 'meh'
}
和一个dataframe
:
我想使用animal
列和mapping
dict以编程方式填充description
列:
def describe_pet(animal,mapping):
return mapping[animal]
当我尝试使用pandasapply()
函数时:
df['description'].apply(describe_pet,args=(df['animal'],mapping))
我得到以下错误:
TypeError: describe_pet() takes exactly 2 arguments (3 given)
似乎使用apply()
将一个参数传递给函数很简单。我怎么能有两个论点呢?在
建议的答案解决了您的具体问题,但对于更一般的情况:
除了列之外,
args
参数还用于参数:pandas.DataFrame.apply
您可以使用
map
方法来完成此操作,而无需编写函数或使用apply
:相关问题 更多 >
编程相关推荐