Python 将函数应用于dataframe中具有两个参数的列
假设我有一个特定的映射:Python 将函数应用于dataframe中具有两个参数的列,python,pandas,Python,Pandas,假设我有一个特定的映射: mapping = { 'cat': 'purrfect', 'dog': 'too much work', 'fish': 'meh' } 和数据帧: animal name description 0 cat sparkles NaN 1 dog rufus NaN 2 fish mr. blub NaN 我想使用animal列和mappingdict作为输
mapping = {
'cat': 'purrfect',
'dog': 'too much work',
'fish': 'meh'
}
和数据帧
:
animal name description
0 cat sparkles NaN
1 dog rufus NaN
2 fish mr. blub NaN
我想使用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()
向函数传递一个参数似乎很简单。如何使用两个参数执行此操作?您可以使用map
方法执行此操作,而无需编写函数或使用apply
:
df['description'] = df.animal.map(mapping)
建议的答案解决了您的具体问题,但对于更一般的情况:
args
参数用于除列之外的参数:
args:除了传递给函数之外,还要传递给函数的元组位置参数
阵列/系列
这非常优雅,当然最适合我的特殊情况。奥菲尔·约克坦的回答适用于更一般的问题。