【问题标题】:select rows from dataframe based on composite logic conditions根据复合逻辑条件从数据框中选择行
【发布时间】:2021-11-16 16:03:36
【问题描述】:

我有一个数据框x,有三列,A, B and C

import pandas as pd
X = pd.DataFrame()
X['A'] = [-100, 0, 2, 3]
X['B'] = [0, -100, 1, 2]
X['C'] = [0, 0, 0, 1]
X

      A     B   C
0   -100    0   0
1    0   -100   0
2    2     1    0
3    3     2    1

我想找到满足以下条件的行,

(If either column A or column B value equals to -100)   OR  (the column C value equals to 1)

就上面的例子而言,[0,1,3]行是我想要得到的

我试过这个,

x1 = ( X[['A','B']]== -100 ) or (X['C'] == 1)

但是得到以下错误信息,应该怎样做才是正确的做法?

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_23048/1363478251.py in <module>
----> 1 x1 = ( X[['A','B']]== -100 ) or (X['C'] == 1)

~\Anaconda3\envs\pyro\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
   1327 
   1328     def __nonzero__(self):
-> 1329         raise ValueError(
   1330             f"The truth value of a {type(self).__name__} is ambiguous. "
   1331             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

【问题讨论】:

    标签: python-3.x pandas dataframe


    【解决方案1】:

    有 2 个错误。

    1. 您不能将or 与系列一起使用,您应该使用按位或:|

    2. 您需要使用 any 聚合左侧部分的比较

    注意。为了清楚起见,我使用了A.eq(B),但这相当于A == B

    x1 = X[['A','B']].eq(-100).any(axis=1) | X['C'].eq(1)
    

    输出:

    0     True
    1     True
    2    False
    3     True
    dtype: bool
    
    切片行

    子选择匹配的行:

    X[x1]
    

    输出:

         A    B  C
    0 -100    0  0
    1    0 -100  0
    3    3    2  1
    

    【讨论】:

      猜你喜欢
      • 2018-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      • 1970-01-01
      • 2013-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多