pandas 条件比较:基于多个列 [英] Pandas conditional comparison: based on multiple columns

查看:63
本文介绍了 pandas 条件比较:基于多个列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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   

我想基于以下内容添加新列:

And I want to add a new column based on:

if (col1 & col2) < (col3 & col4) --- > 2

我遵循的方法类似于这篇帖子,只是没有如下的 max(),但都没有用:

I followed the approach similar to this post, just without max() as follow but all didn't work:

df[['col1','col2']] < df[['col3','col4']] 

(df['col1'] and df['col2']) < (df['col3'] and df['col4'])

正确的方法是什么?谢谢.

What's the correct way to do it? Thanks.

推荐答案

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

这篇关于 pandas 条件比较:基于多个列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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