How to apply a function to two columns of Pandas dataframe

前端 未结 12 1184
名媛妹妹
名媛妹妹 2020-11-22 06:17

Suppose I have a df which has columns of \'ID\', \'col_1\', \'col_2\'. And I define a function :

f = lambda x, y : my_function_expres

12条回答
  •  孤独总比滥情好
    2020-11-22 06:33

    I'm sure this isn't as fast as the solutions using Pandas or Numpy operations, but if you don't want to rewrite your function you can use map. Using the original example data -

    import pandas as pd
    
    df = pd.DataFrame({'ID':['1','2','3'], 'col_1': [0,2,3], 'col_2':[1,4,5]})
    mylist = ['a','b','c','d','e','f']
    
    def get_sublist(sta,end):
        return mylist[sta:end+1]
    
    df['col_3'] = list(map(get_sublist,df['col_1'],df['col_2']))
    #In Python 2 don't convert above to list
    

    We could pass as many arguments as we wanted into the function this way. The output is what we wanted

    ID  col_1  col_2      col_3
    0  1      0      1     [a, b]
    1  2      2      4  [c, d, e]
    2  3      3      5  [d, e, f]
    

提交回复
热议问题