通过在两个现有列上使用lambda函数在Panda中创建新列 [英] Creating a new column in Panda by using lambda function on two existing columns

查看:175
本文介绍了通过在两个现有列上使用lambda函数在Panda中创建新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过定义用户功能然后使用apply在Panda中添加新列.但是,我想使用 lambda 做到这一点;有办法吗?

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?

例如,df具有两列ab.我想创建一个新列c,该列等于ab之间的最长长度.

For Example, df has two columns a and b. I want to create a new column c which is equal to the longest length between a and b.

类似:

df['c'] = df.apply(lambda x, len(df['a']) if len(df['a']) > len(df['b']) or len(df['b']) )

一种方法:

df = pd.DataFrame({'a':['dfg','f','fff','fgrf','fghj'], 'b' : ['sd','dfg','edr','df','fghjky']})

df['c'] = df.apply(lambda x: max([len(x) for x in [df['a'], df['b']]]))
print df
      a       b   c
0   dfg      sd NaN
1     f     dfg NaN
2   fff     edr NaN
3  fgrf      df NaN
4  fghj  fghjky NaN

推荐答案

您可以使用函数更多信息

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

下一个解决方案是使用功能应用参数axis=1:

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

axis = 1或"columns":将功能应用于每一行

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

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

这篇关于通过在两个现有列上使用lambda函数在Panda中创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆