Python Pandas:多列上的布尔索引

时间:2013-06-20 14:21:32

标签: python pandas dataframe

尽管有关于如何在Python的pandas库中索引DataFrame的至少two good教程,我仍然无法找到SELECT的优雅方式不止一列。

>>> 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的方式?

2 个答案:

答案 0 :(得分:65)

这是一个优先的运营商问题。

您应该添加额外的括号以使您的多项条件测试有效:

d[(d['x']>2) & (d['y']>7)]
您提到的教程的

This section显示了一个带有几个布尔条件的示例,并使用了括号。

答案 1 :(得分:1)

可能还有更好的方法,但

In [56]: d[d['x'] > 2] and d[d['y'] > 7]
Out[56]: 
   x  y
4  5  8

作品。

相关问题