When should I (not) want to use pandas apply() in my code?

后端 未结 4 770
悲哀的现实
悲哀的现实 2020-11-21 05:19

I have seen many answers posted to questions on Stack Overflow involving the use of the Pandas method apply. I have also seen users commenting under them saying

4条回答
  •  [愿得一人]
    2020-11-21 05:44

    Are there ever any situations where apply is good? Yes, sometimes.

    Task: decode Unicode strings.

    import numpy as np
    import pandas as pd
    import unidecode
    
    s = pd.Series(['mañana','Ceñía'])
    s.head()
    0    mañana
    1     Ceñía
    
    
    s.apply(unidecode.unidecode)
    0    manana
    1     Cenia
    

    Update
    I was by no means advocating for the use of apply, just thinking since the NumPy cannot deal with the above situation, it could have been a good candidate for pandas apply. But I was forgetting the plain ol list comprehension thanks to the reminder by @jpp.

提交回复
热议问题