python – 熊猫中的相对行选择?

是否可以在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%

点赞