我有一个df
col1 col2 col3 col4
0 1 2 3 4
1 2 2 3 4
2 3 4 3 5
3 4 3 2 1
我想基于以下内容添加新列:
if (col1 & col2) < (col3 & col4) --- > 2
我遵循了类似于this post的方法,只是没有遵循max()
,但都没有用:
df[['col1','col2']] < df[['col3','col4']]
(df['col1'] and df['col2']) < (df['col3'] and df['col4'])
正确的方法是什么?谢谢。
答案 0 :(得分:1)
mask = df[['col1','col2']].max(1) < df[['col3','col4']].min(1)
df['new_col'] = np.where(mask, 2, np.nan)
输出:
col1 col2 col3 col4 new_col
0 1 2 3 4 2.0
1 2 2 3 4 2.0
2 3 4 3 5 NaN
3 4 3 2 1 NaN