【问题标题】:Filtering pandas dataframe with multiple Boolean columns使用多个布尔列过滤熊猫数据框
【发布时间】:2018-02-22 18:06:51
【问题描述】:

我正在尝试使用作为 df 一部分的几个布尔变量过滤 df,但无法这样做。

样本数据:

A | B | C | D
John Doe | 45 | True | False
Jane Smith | 32 | False | False
Alan Holmes | 55 | False | True
Eric Lamar | 29 | True | True

C 和 D 列的 dtype 是布尔值。我想创建一个新的 df (df1),其中只有 C 或 D 为 True 的行。它应该是这样的:

A | B | C | D
John Doe | 45 | True | False
Alan Holmes | 55 | False | True
Eric Lamar | 29 | True | True

我尝试过类似的方法,但由于无法处理布尔类型而面临问题:

df1 = df[(df['C']=='True') or (df['D']=='True')]

有什么想法吗?

【问题讨论】:

  • bool 类型应该不加引号引用,除非它存储为字符串

标签: python pandas numpy dataframe boolean


【解决方案1】:
In [82]: d
Out[82]:
             A   B      C      D
0     John Doe  45   True  False
1   Jane Smith  32  False  False
2  Alan Holmes  55  False   True
3   Eric Lamar  29   True   True

解决方案 1:

In [83]: d.loc[d.C | d.D]
Out[83]:
             A   B      C      D
0     John Doe  45   True  False
2  Alan Holmes  55  False   True
3   Eric Lamar  29   True   True

解决方案 2:

In [94]: d[d[['C','D']].any(1)]
Out[94]:
             A   B      C      D
0     John Doe  45   True  False
2  Alan Holmes  55  False   True
3   Eric Lamar  29   True   True

解决方案 3:

In [95]: d.query("C or D")
Out[95]:
             A   B      C      D
0     John Doe  45   True  False
2  Alan Holmes  55  False   True
3   Eric Lamar  29   True   True

PS 如果您将解决方案更改为:

df[(df['C']==True) | (df['D']==True)]

它也会起作用

Pandas docs - boolean indexing


why we should NOT use "PEP complaint" df["col_name"] is True instead of df["col_name"] == True?

In [11]: df = pd.DataFrame({"col":[True, True, True]})

In [12]: df
Out[12]:
    col
0  True
1  True
2  True

In [13]: df["col"] is True
Out[13]: False               # <----- oops, that's not exactly what we wanted

【讨论】:

  • 啊!就在我要发布确切答案的时候:)
  • 伙计,我想大多数提问者都被我们宠坏了...:) 很好的解决方案
  • df[(df.var == True)].count() 为我触发 E712(使用是 True 而不是 ==)
  • @kev,感谢您的建议,但(df['C'] is True)始终返回False,与数据无关。我认为这不会改善我的答案;)
  • @kev,我不会故意破坏代码(df["col_name"] is True - 产生错误结果)只是为了成为 PEP 投诉。我在答案中添加了一个示例。顺便说一句,我的回答中有三个选项,所有选项都是 PEP 投诉;)
【解决方案2】:

万岁!更多选择!

np.where

df[np.where(df.C | df.D, True, False)]

             A   B      C      D
0     John Doe  45   True  False
2  Alan Holmes  55  False   True
3   Eric Lamar  29   True   True  

pd.Series.where df.index

df.loc[df.index.where(df.C | df.D).dropna()]

               A   B      C      D
0.0     John Doe  45   True  False
2.0  Alan Holmes  55  False   True
3.0   Eric Lamar  29   True   True

df.select_dtypes

df[df.select_dtypes([bool]).any(1)]   

             A   B      C      D
0     John Doe  45   True  False
2  Alan Holmes  55  False   True
3   Eric Lamar  29   True   True

滥用np.select

df.iloc[np.select([df.C | df.D], [df.index])].drop_duplicates()

             A   B      C      D
0     John Doe  45   True  False
2  Alan Holmes  55  False   True
3   Eric Lamar  29   True   True

【讨论】:

  • @Wen 这些解决方案中的大多数都很糟糕,但我很高兴找到它们。我认为np.where 是最好的。
  • 酷!我永远不会想到“np.select”+1 :)
【解决方案3】:

或者

d[d.eval('C or D')]

Out[1065]:
             A   B      C      D
0     John Doe  45   True  False
2  Alan Holmes  55  False   True
3   Eric Lamar  29   True   True

【讨论】:

  • 评估,这是我的第一选择! (在此之后不得不寻找另一个)
【解决方案4】:

所以,最简单的方法是:

students = [ ('jack1', 'Apples1' , 341) ,
             ('Riti1', 'Mangos1'  , 311) ,
             ('Aadi1', 'Grapes1' , 301) ,
             ('Sonia1', 'Apples1', 321) ,
             ('Lucy1', 'Mangos1'  , 331) ,
             ('Mike1', 'Apples1' , 351),
              ('Mik', 'Apples1' , np.nan)
              ]
#Create a DataFrame object
df = pd.DataFrame(students, columns = ['Name1' , 'Product1', 'Sale1']) 
print(df)


    Name1 Product1  Sale1
0   jack1  Apples1    341
1   Riti1  Mangos1    311
2   Aadi1  Grapes1    301
3  Sonia1  Apples1    321
4   Lucy1  Mangos1    331
5   Mike1  Apples1    351
6     Mik  Apples1    NaN

# Select rows in above DataFrame for which ‘Product’ column contains the value ‘Apples’,
subset = df[df['Product1'] == 'Apples1']
print(subset)

 Name1 Product1  Sale1
0   jack1  Apples1    341
3  Sonia1  Apples1    321
5   Mike1  Apples1    351
6     Mik  Apples1    NA

# Select rows in above DataFrame for which ‘Product’ column contains the value ‘Apples’, AND notnull value in Sale

subsetx= df[(df['Product1'] == "Apples1")  & (df['Sale1'].notnull())]
print(subsetx)
    Name1   Product1    Sale1
0   jack1   Apples1      341
3   Sonia1  Apples1      321
5   Mike1   Apples1      351

# Select rows in above DataFrame for which ‘Product’ column contains the value ‘Apples’, AND Sale = 351

subsetx= df[(df['Product1'] == "Apples1")  & (df['Sale1'] == 351)]
print(subsetx)

   Name1 Product1  Sale1
5  Mike1  Apples1    351

# Another example
subsetData = df[df['Product1'].isin(['Mangos1', 'Grapes1']) ]
print(subsetData)

Name1 Product1  Sale1
1  Riti1  Mangos1    311
2  Aadi1  Grapes1    301
4  Lucy1  Mangos1    331

这里是这段代码的来源:https://thispointer.com/python-pandas-select-rows-in-dataframe-by-conditions-on-multiple-columns/
我对其进行了一些小改动。

【讨论】:

    【解决方案5】:

    您可以轻松尝试:

    df1 = df[(df['C']=='True') | (df['D']=='True')]
    

    注意:

    1. or 逻辑运算符需要替换为按位| 运算符。
    2. 确保使用() 括住每个操作数。

    【讨论】:

    • 这类似于半年前已经给出的答案并且不起作用。请下次尝试使用示例数据。
    猜你喜欢
    • 1970-01-01
    • 2019-07-20
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    相关资源
    最近更新 更多