pandas df中的多个逻辑比较 [英] Multiple logical comparisons in pandas df
本文介绍了 pandas df中的多个逻辑比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有以下熊猫df
If I have the following pandas df
A B C D
1 2 3 4
2 2 3 4
并且我想根据需要添加新列为1、2或3,
and I want to add a new column to be 1, 2 or 3 depending on,
(A > B) && (B > C) = 1
(A < B) && (B < C) = 2
Else = 3
什么是最好的方法?
推荐答案
You can use numpy.select
to structure your multiple conditions. The final parameter represents default value.
conditions = [(df.A > df.B) & (df.B > df.C),
(df.A < df.B) & (df.B < df.C)]
values = [1, 2]
df['E'] = np.select(conditions, values, 3)
有几种选择:嵌套的 numpy.where
,顺序的 pd.DataFrame.loc
, pd.DataFrame.apply
.此解决方案的主要优点是可读性,同时保持向量化.
There are several alternatives: nested numpy.where
, sequential pd.DataFrame.loc
, pd.DataFrame.apply
. The main benefit of this solution is readability while remaining vectorised.
这篇关于 pandas df中的多个逻辑比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文