将函数应用于带有两个参数的pandas数据框中的列 [英] Apply function to column in pandas dataframe that takes two arguments

查看:102
本文介绍了将函数应用于带有两个参数的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:

args:元组除参数外还传递给函数的位置参数 数组/系列

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

pandas.DataFrame.apply

这篇关于将函数应用于带有两个参数的pandas数据框中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆