Creating a new column in Panda by using lambda function on two existing columns

前端 未结 1 765
盖世英雄少女心
盖世英雄少女心 2021-02-04 01:24

I am able to add a new column in Panda by defining user function and then using apply. However, I want to do this using lambda; is there a way around?

For Examp

1条回答
  •  时光说笑
    2021-02-04 02:08

    You can use function map and select by function np.where more info

    print df
    #     a     b
    #0  aaa  rrrr
    #1   bb     k
    #2  ccc     e
    #condition if condition is True then len column a else column b
    df['c'] = np.where(df['a'].map(len) > df['b'].map(len), df['a'].map(len), df['b'].map(len))
    print df
    #     a     b  c
    #0  aaa  rrrr  4
    #1   bb     k  2
    #2  ccc     e  3
    

    Next solution is with function apply with parameter axis=1:

    axis = 1 or ‘columns’: apply function to each row

    df['c'] = df.apply(lambda x: max(len(x['a']), len(x['b'])), axis=1)
    

    0 讨论(0)
提交回复
热议问题