【发布时间】: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