【发布时间】:2013-06-17 10:59:48
【问题描述】:
尽管至少有twogood 教程介绍了如何在 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 的方法?
【问题讨论】: