python - Pandas 中的相对行选择?

标签 python pandas

如果符合特定条件,是否可以在 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/

相关文章:

python - Pandas - 巨大的内存消耗

python - 删除具有 3 个或更多列且为 0 的记录

python - 从列表组合生成 Python 字典

python - 将多个 lambda 函数与 pandas 数据框一起使用

python - 如何从 scrapy 中的 json 文件中读取行

python - 子图上的 x 轴标题 Plotly Python

python - Flask 用户管理 : How to make Stateless Server using better authentication ways?

python - 是否可以为 redis 键设置过期时间(批量操作)

python - 在python中根据时间对两个日志数据数组进行排序

python - 同时从两列中减去值( Pandas , python )