我有一个名为 count 的方法,它需要 2 个参数。我需要使用 apply() 方法来调用此方法。但是,当我将两个参数传递给 apply 方法时,出现以下错误:
类型错误:counting() 恰好需要 2 个参数(给定 1 个)
我看过以下主题python pandas:将带有参数的函数应用于一系列。更新 https://stackoverflow.com/questions/21188504/python-pandas-apply-a-function-with-arguments-to-a-series-update?lq=1我不想使用 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')
如果我给出一个参数,它就会起作用:
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
here:
from functools import partial
count_word = partial(counting, strWord='word')
DF['new_column'] = DF['dic_column'].apply(count_word)
正如@EdChum 提到的,如果你counting
方法实际上只是查找一个单词或将其默认为零,您可以使用方便的dict.get
方法而不是自己写一个:
DF['new_column'] = DF['dic_column'].apply(lambda dic: dic.get('word', 0))
和一个非lambda
执行上述操作的方法,通过operator
module:
from operator import methodcaller
count_word = methodcaller(get, 'word', 0)
DF['new_column'] = DF['dic_column'].apply(count_word)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)