pandas 如何将多个参数传递给 apply 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33204763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass multiple arguments to the apply function
提问by Bonson
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:
我有一个叫做计数的方法,它接受 2 个参数。我需要使用 apply() 方法调用此方法。但是,当我将这两个参数传递给 apply 方法时,出现以下错误:
TypeError: counting() takes exactly 2 arguments (1 given)
类型错误:counting() 正好需要 2 个参数(给定 1 个)
I have seen the following thread python pandas: apply a function with arguments to a series. Updateand I do not want to use functool.partial as I do not want to import additional classes to be able to pass parameters.
我见过以下线程python pandas: apply a function with arguments to a series。更新,我不想使用 functool.partial 因为我不想导入额外的类来传递参数。
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)
回答by tzaman
You could just use a lambda:
你可以只使用一个lambda:
DF['new_column'] = DF['dic_column'].apply(lambda dic: counting(dic, 'word'))
On the other hand, there's absolutely nothing wrong with using partialhere:
另一方面,在partial这里使用绝对没有错:
from functools import partial
count_word = partial(counting, strWord='word')
DF['new_column'] = DF['dic_column'].apply(count_word)
As @EdChum mentions, if your countingmethod is actually just looking up a word or defaulting it to zero, you can just use the handy dict.getmethod instead of writing one yourself:
正如@EdChum 提到的,如果您的counting方法实际上只是查找一个单词或将其默认为零,您可以使用方便的dict.get方法而不是自己编写一个:
DF['new_column'] = DF['dic_column'].apply(lambda dic: dic.get('word', 0))
And a non-lambdaway to do the above, via the operatormodule:
并且lambda通过operator模块执行上述操作的非方法:
from operator import methodcaller
count_word = methodcaller(get, 'word', 0)
DF['new_column'] = DF['dic_column'].apply(count_word)
回答by L0j1k
The accepted answer is totally perfect. Taught me some interesting things about Python. But just for fun, here's more precisely what we're looking for:
接受的答案是完全完美的。教会了我一些关于 Python 的有趣事情。但只是为了好玩,以下是我们正在寻找的更准确的信息:
selected_words = ['awesome', 'great', 'fantastic', 'amazing', 'love', 'horrible', 'bad', 'terrible', 'awful', 'wow', 'hate']
for this_word in selected_words:
products[this_word] = products['word_count'].apply(lambda dic: dic.get(this_word, 0))
Thanks for posting the question!
感谢您发布问题!

