Python Pandas : Boolean indexing on multiple columns

标签 python pandas dataframe

尽管至少有 two good关于如何在 Python 的 pandas 库中索引 DataFrame 的教程,我仍然无法找到一种优雅的方式来对多个列进行 SELECTing。

>>> d = pd.DataFrame({'x':[1, 2, 3, 4, 5], 'y':[4, 5, 6, 7, 8]})
>>> d
   x  y
0  1  4
1  2  5
2  3  6
3  4  7
4  5  8
>>> d[d['x']>2] # This works fine
   x  y
2  3  6
3  4  7
4  5  8
>>> d[d['x']>2 & d['y']>7] # I had expected this to work, but it doesn't
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我发现(我认为是)一种相当不雅的方式,像这样

>>> d[d['x']>2][d['y']>7]

但它并不漂亮,而且它的可读性得分相当低(我认为)。

有没有更好、更符合 Python 的方法?

最佳答案

这是一个优先运算符问题。

您应该添加额外的括号以使您的多条件测试正常工作:

d[(d['x']>2) & (d['y']>7)]

This section您提到的教程中显示了一个带有几个 bool 条件的示例,并使用了括号。

关于Python Pandas : Boolean indexing on multiple columns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17216153/

相关文章:

python - 使用 PySpark 从 API 响应创建表

python - 安装工具:从父目录中查找 SVN 修订版

python - 使用键盘移动图像

python - 用于线性回归的 TensorFlow 导入数据

Github 拉取请求的指数平滑(工作代码)的 Python Numpy 迭代改进

python - 基于多列的 Pandas 多个条件

python - 在 python pandas 中迭代非常大的数据帧效率太耗时

python - 如何在sequel server management studio 2017中使用正确的语法直接运行python代码

python - 识别 python DataFrame 中相等的行...

python - 分组(按)值的 Pandas 直方图(计数)