将函数应用于带有两个参数的 pandas 数据框中的列

2023-12-27

假设我有一定的映射:

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

and a dataframe:

    animal  name       description
0   cat     sparkles   NaN
1   dog     rufus      NaN
2   fish    mr. blub   NaN

我想以编程方式填写description列使用animal列和mapping字典作为输入:

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 at all:

df['description'] = df.animal.map(mapping)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将函数应用于带有两个参数的 pandas 数据框中的列 的相关文章

随机推荐