通过在两个现有列上使用lambda函数在Panda中创建新列

piy*_*rma 16 python lambda calculated-columns multiple-columns pandas

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

例如,df有两列a和b.我想创建一个新列c,它等于a和之间的最长长度b.

就像是:

df['c'] = df.apply(lambda x, len(df['a']) if len(df['a']) > len(df['b']) or len(df['b']) )
Run Code Online (Sandbox Code Playgroud)

一种方法:

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
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 16

您可以使用功能图并按功能选择np.where 更多信息

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
Run Code Online (Sandbox Code Playgroud)

下一个解决方案是使用函数apply with parameter axis=1:

axis = 1或'columns':将函数应用于每一行

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

  • 对于未来的读者来说,错误是忘记了 axis = 1(当我们迭代 row_indexer [0,1,2,3,4] 时,这导致了 KeyError 'a')而不是 df['a'], df ['b']。而且 Jezraels Solution#2 更简洁一些,因为 lambda 已经循环遍历了行。 (2认同)