Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/reporting-services/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将函数应用于dataframe中具有两个参数的列_Python_Pandas - Fatal编程技术网

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]
当我尝试使用pandas
apply()
函数时:

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:除了传递给函数之外,还要传递给函数的元组位置参数 阵列/系列


这非常优雅,当然最适合我的特殊情况。奥菲尔·约克坦的回答适用于更一般的问题。