How to pass multiple arguments to the apply function

后端 未结 2 2052
囚心锁ツ
囚心锁ツ 2021-02-08 07:09

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

2条回答
  •  后悔当初
    2021-02-08 07:28

    You could just use a lambda:

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

    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)
    

    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))
    

    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)
    

提交回复
热议问题