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
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)
| 归档时间: |
|
| 查看次数: |
29054 次 |
| 最近记录: |