【问题标题】:python dataframe filtering combination of or and andpython数据框过滤or和and的组合
【发布时间】:2021-10-07 21:40:55
【问题描述】:

我正在尝试根据以下条件过滤数据框:

colA = 阿尔法或贝塔

colB = 伽马

我尝试了以下方法

filtered_df = (df[(df['colA'] == 'alpha') & (df['colB'] == 'gamma')]) | (df[(df['colA'] == 'beta') & (df['colB'] == 'gamma')])

但这不起作用,我收到以下错误消息:

TypeError: unsupported operand type(s) for |: 'str' and 'bool'

实现预期结果的最 Pythonic 方式是什么?

谢谢!

【问题讨论】:

  • 问题在于,当您输入 df[(df['colA'] == 'alpha') & (df['colB'] == 'gamma')] 时,它会返回该语句的 True 值。正如错误所说,这些不是布尔值。
  • 这是对您的公式的更正,尽管@AnuragDabas 有更好的解决方案。 df[((df['colA'] == 'alpha') & (df['colB'] == 'gamma')) | ((df['colA'] == 'beta') & (df['colB'] == 'gamma'))]

标签: python pandas dataframe filtering


【解决方案1】:

你可以试试loc+isin()+eq():

filtered_df =df.loc[(df['colA'].isin(['alpha','beta'])) & (df['colB'].eq('gamma'))]

现在,如果您打印 filtered_df,您将获得过滤后的数据框

【讨论】:

    【解决方案2】:

    你可以试试这样的。

    df.loc[((df['colA'] == 'alpha') | (df['colA'] == 'beta')) & (df['colB'] == 'gamma')]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-11
      • 1970-01-01
      • 1970-01-01
      • 2014-04-18
      • 1970-01-01
      • 2018-06-03
      相关资源
      最近更新 更多