pandas :过滤多个条件 [英] Pandas: Filtering multiple conditions
本文介绍了 pandas :过滤多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Pandas在几个条件下进行布尔索引.我原来的DataFrame称为df
.如果执行以下操作,将会得到预期的结果:
I'm trying to do boolean indexing with a couple conditions using Pandas. My original DataFrame is called df
. If I perform the below, I get the expected result:
temp = df[df["bin"] == 3]
temp = temp[(~temp["Def"])]
temp = temp[temp["days since"] > 7]
temp.head()
但是,如果我这样做(我认为应该是等效的),我将没有返回任何行:
However, if I do this (which I think should be equivalent), I get no rows back:
temp2 = df[df["bin"] == 3]
temp2 = temp2[~temp2["Def"] & temp2["days since"] > 7]
temp2.head()
任何主意是什么造成了差异?
Any idea what accounts for the difference?
推荐答案
使用()
,因为运算符优先级:
temp2 = df[~df["Def"] & (df["days since"] > 7) & (df["bin"] == 3)]
或者,在单独的行上创建条件:
Alternatively, create conditions on separate rows:
cond1 = df["bin"] == 3
cond2 = df["days since"] > 7
cond3 = ~df["Def"]
temp2 = df[cond1 & cond2 & cond3]
示例:
df = pd.DataFrame({'Def':[True] *2 + [False]*4,
'days since':[7,8,9,14,2,13],
'bin':[1,3,5,3,3,3]})
print (df)
Def bin days since
0 True 1 7
1 True 3 8
2 False 5 9
3 False 3 14
4 False 3 2
5 False 3 13
temp2 = df[~df["Def"] & (df["days since"] > 7) & (df["bin"] == 3)]
print (temp2)
Def bin days since
3 False 3 14
5 False 3 13
这篇关于 pandas :过滤多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文