【问题标题】:How to fllter a pandas DataFrame by multiple columns?如何按多列过滤熊猫数据框?
【发布时间】:2018-07-13 14:42:46
【问题描述】:

我正在尝试根据两个逻辑语句在 python 中对 pandas DataFrame 进行子集化

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
df[df.col1 = 1 and df.col2 = 3]

但我在第 3 行收到无效语法。

有没有办法在一行中做到这一点?

【问题讨论】:

标签: python pandas


【解决方案1】:

免责声明: 正如@jp_data_analysis 和pandas docs 所提到的,以下解决方案不是最好的,因为它使用了链式索引。请参考 Matt W. 和 AChampion 的解决方案。

另一种单线解决方案。

>>> d = {'col1': [1, 2, 1], 'col2': [3, 4, 2]}
>>> df = pd.DataFrame(data=d)

>>> df[df.col1==1][df.col2==3]

   col1  col2
0     1     3

我添加了第三行,'col1'=1'col2'=2,所以我们可以有一个额外的否定测试用例。

【讨论】:

  • downvoted - 链式索引被广泛劝阻,请参阅pandas docs 了解原因。
  • 你是对的@jp_data_analysis。我已将此信息添加到原始答案中。
【解决方案2】:

您需要使用逻辑运算符。 == 等于返回布尔值,= 正在设置一个值。

试试:

df[(df.col1 == 1) & (df.col2 == 3)]

【讨论】:

  • 您需要在每个表达式周围添加(),否则会出现相同的错误。还要注意按位 & 与逻辑 and 运算符的使用。
猜你喜欢
  • 2014-03-31
  • 1970-01-01
  • 2017-12-15
  • 2019-04-13
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 2015-09-24
相关资源
最近更新 更多