How to apply a function to two columns of Pandas dataframe

前端 未结 12 1364
名媛妹妹
名媛妹妹 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:25

    A interesting question! my answer as below:

    import pandas as pd
    
    def sublst(row):
        return lst[row['J1']:row['J2']]
    
    df = pd.DataFrame({'ID':['1','2','3'], 'J1': [0,2,3], 'J2':[1,4,5]})
    print df
    lst = ['a','b','c','d','e','f']
    
    df['J3'] = df.apply(sublst,axis=1)
    print df
    

    Output:

      ID  J1  J2
    0  1   0   1
    1  2   2   4
    2  3   3   5
      ID  J1  J2      J3
    0  1   0   1     [a]
    1  2   2   4  [c, d]
    2  3   3   5  [d, e]
    

    I changed the column name to ID,J1,J2,J3 to ensure ID < J1 < J2 < J3, so the column display in right sequence.

    One more brief version:

    import pandas as pd
    
    df = pd.DataFrame({'ID':['1','2','3'], 'J1': [0,2,3], 'J2':[1,4,5]})
    print df
    lst = ['a','b','c','d','e','f']
    
    df['J3'] = df.apply(lambda row:lst[row['J1']:row['J2']],axis=1)
    print df
    

提交回复
热议问题