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

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


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 bdf['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)