如果符合特定条件,是否可以在 pandas 中选择特定行之前/之后的 5 行?
例如,是否可以从第 19 行开始,然后选择 b 为 True 的前五行(因此选择 16、16、10、7 和 4)。我会称之为“相对”位置。 (有更好的术语吗?我可以阅读有关此类查找的地方?)
a | b
=============
0 True
1 False
4 True
7 True
9 False
10 True
13 True
16 True
18 False
19 True
最佳答案
试试这个:
In [31]: df.ix[(df.b) & (df.index < df[df.a == 19].index[0])].tail(5)
Out[31]:
a b
2 4 True
3 7 True
5 10 True
6 13 True
7 16 True
一步一步:
a==19 的元素索引:
In [32]: df[df.a == 19].index[0]
Out[32]: 9
现在我们可以列出所有 b 为 True
且索引小于 9 的元素:
In [30]: df.ix[(df.b) & (df.index <9)].tail(5)
Out[30]:
a b
2 4 True
3 7 True
5 10 True
6 13 True
7 16 True
现在将它们结合起来:
In [33]: df.ix[(df.b) & (df.index < df[df.a == 19].index[0])].tail(5)
Out[33]:
a b
2 4 True
3 7 True
5 10 True
6 13 True
7 16 True
稍微加快一点:
In [103]: idx19 = df[df.a == 19].index[0]
In [104]: idx19
Out[104]: 9
In [107]: %timeit df.ix[(df.b) & (df.index < df[df.a == 19].index[0])].tail(5)
1000 loops, best of 3: 973 µs per loop
In [108]: %timeit df.ix[(df.b) & (df.index < idx19)].tail(5)
1000 loops, best of 3: 564 µs per loop
PS 所以它快了 42%
关于python - Pandas 中的相对行选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36187607/