更新时间:2023-02-11 14:26:16
您可以只使用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)