本文介绍了将函数应用于带有两个参数的pandas数据框中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有一个特定的映射:
Say I have a certain mapping:
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
我想使用animal
列和mapping
dict作为输入以编程方式填写description
列:
I would like to programmatically fill in the description
column using the animal
column and mapping
dict as inputs:
def describe_pet(animal,mapping):
return mapping[animal]
当我尝试使用熊猫apply()
函数时:
When I try to use pandas apply()
function:
df['description'].apply(describe_pet,args=(df['animal'],mapping))
我收到以下错误:
TypeError: describe_pet() takes exactly 2 arguments (3 given)
使用apply()
似乎很简单,将一个参数传递给函数.我该如何使用两个参数呢?
It seems like using apply()
is trivial passing one argument to the function. How can I do it with two arguments?
推荐答案
建议的答案解决了您的特定问题,但对于更通用的情况:
The suggested answer solves your specific problem, but for the more generic case:
args
参数用于除列之外的参数:
The args
parameter is for parameters in addition to the columns:
这篇关于将函数应用于带有两个参数的pandas数据框中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!