我有一个叫做counting的方法,它有两个参数。我需要使用apply()方法调用这个方法。但是,当我将这两个参数传递给apply方法时,它会给出以下错误:
TypeError: counting() takes exactly 2 arguments (1 given)
我已经看到下面的线程python pandas: apply a function with arguments to a series. Update,我不想使用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)
公认的答案是完全完美的。教了我一些关于Python的有趣的东西。但只是为了好玩,我们要找的更准确:
谢谢你把问题贴出来!
您可以使用
lambda
:另一方面,在这里使用
partial
绝对没有问题:正如@EdChum提到的,如果您的
counting
方法实际上只是查找一个单词或将其默认为零,那么您可以使用方便的dict.get
方法而不是自己编写一个:以及通过
operator
模块执行上述操作的非lambda
方法:相关问题 更多 >
编程相关推荐