将函数应用于pandas dataframe中接受两个参数的列

2024-04-26 14:45:18 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个特定的映射:

mapping = {
    'cat': 'purrfect',
    'dog': 'too much work',
    'fish': 'meh'
    }

和一个dataframe

^{pr2}$

我想使用animal列和mappingdict以编程方式填充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()将一个参数传递给函数很简单。我怎么能有两个论点呢?在


Tags: 函数dfdescriptionmappingcatworktooapply
2条回答

建议的答案解决了您的具体问题,但对于更一般的情况:

除了列之外,args参数还用于参数:

args : tuple Positional arguments to pass to function in addition to the array/series

pandas.DataFrame.apply

您可以使用map方法来完成此操作,而无需编写函数或使用apply

df['description'] = df.animal.map(mapping)

相关问题 更多 >