如何将多个参数传递给apply函数 [英] How to pass multiple arguments to the apply function

查看:641
本文介绍了如何将多个参数传递给apply函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个称为计数的方法,该方法需要2个参数.我需要使用apply()方法来调用此方法.但是,当我将两个参数传递给apply方法时,它给出了以下错误:

I have a method called counting that takes 2 arguments. I need to call this method using the apply() method. However when I am passing the two parameters to the apply method it is giving the following error:

TypeError:counting()恰好接受2个参数(给定1个参数)

TypeError: counting() takes exactly 2 arguments (1 given)

我看过以下线程

I have seen the following thread python pandas: apply a function with arguments to a series. Update and I do not want to use functool.partial as I do not want to import additional classes to be able to pass parameters.

def counting(dic, strWord):
    if strWord in dic:
        return dic[strWord]
    else:
        return 0

DF['new_column'] = DF['dic_column'].apply(counting, 'word')

如果我给出一个参数,它将起作用:

If I give a single parameter, it works:

def awesome_count(dic):
    if strWord in dic:
       return dic[strWord]
    else:
       return 0

DF['new_column'] = DF['dic_column'].apply(counting)

推荐答案

您可以只使用lambda:

DF['new_column'] = DF['dic_column'].apply(lambda dic: counting(dic, 'word'))

另一方面,在这里使用partial绝对没有错:

On the other hand, there's absolutely nothing wrong with using partial here:

from functools import partial
count_word = partial(counting, strWord='word')
DF['new_column'] = DF['dic_column'].apply(count_word)

正如@EdChum所述,如果您的counting方法实际上只是查找一个单词或将其默认设置为零,则可以使用方便的dict.get方法来代替自己写一个:

As @EdChum mentions, if your counting method is actually just looking up a word or defaulting it to zero, you can just use the handy dict.get method instead of writing one yourself:

DF['new_column'] = DF['dic_column'].apply(lambda dic: dic.get('word', 0))

以及通过operator模块执行上述操作的非lambda方式:

And a non-lambda way to do the above, via the operator module:

from operator import methodcaller
count_word = methodcaller(get, 'word', 0)
DF['new_column'] = DF['dic_column'].apply(count_word)

这篇关于如何将多个参数传递给apply函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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