简体   繁体   English

基于多个条件过滤 Dataframe 结果

[英]Filtering Dataframe Results Based on Multiple Conditions

I am struggling with filtering dataframe results set based on multiple conditions and would appreciate your help on the case below.我正在努力根据多个条件过滤 dataframe 结果集,并感谢您对以下案例的帮助。

In the example below I would like to filter based on two conditions in dataframe:在下面的示例中,我想根据 dataframe 中的两个条件进行过滤:

  1. Column "Condition 1" = 1 “条件 1”列 = 1
  2. Column "Condition 2" = 0 “条件 2”列 = 0

In the code I use the following logic to filter the results with "filt" variable:在代码中,我使用以下逻辑通过“filt”变量过滤结果:

filt = (df["Condition 1"] )== 1 & (df["Condition 2"] == 0)

Unfortunately, the two-condition filter does not yield the desired results.不幸的是,双条件过滤器不会产生预期的结果。 In fact, neither conditions 1 nor 2 are met in the output.事实上,在 output 中,条件 1 和 2 都不满足。

print(df.loc[filt, "Condition 3"])

An alternative approach that worked but I would like to avoid is to create a third condition where "Condition 1" - "Condition 2" = 1 and base a filter on it.另一种可行但我想避免的方法是创建第三个条件,其中“条件 1”-“条件 2”= 1并以此为基础进行过滤。 This would look as follows:这将如下所示:

filt2 = df["Condition 3"] == 1

print(df.loc[filt2, "Condition 3"])

Notice that in this case there is only one condition in the filter ("filt2") which eventually produces the expected results.请注意,在这种情况下,过滤器(“filt2”)中只有一个条件最终会产生预期的结果。

My questions are:我的问题是:

  1. Is there a reason that the multiple (two) filters do not work in my example, while the single condition filter does?在我的示例中,多个(两个)过滤器不起作用,而单个条件过滤器起作用,是否有原因? Is there something I am overlooking in the code?我在代码中忽略了什么?
  2. Are there better and simpler solutions to the alternative approach used with creating a third condition?对于用于创建第三种条件的替代方法,是否有更好和更简单的解决方案?

PS: The code below on "filt" would also produce the expected results. PS:下面关于“filt”的代码也会产生预期的结果。

filt = df["Condition 1"] - df["Condition 2"] == 1

You should filter like this:你应该像这样过滤:

filt = df[(df["Condition 1"] == 1) & (df["Condition 2"] == 0)]

filt dataframe will contain the desired result filt dataframe 将包含所需的结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM