熊猫在布尔索引匹配周围获得N行

时间:2019-09-13 01:11:21

标签: python pandas indexing

请考虑以下内容

import pandas

data = pandas.Series([1,2,3,4,5,6,7,12,13,14,15,18,19])

diffs = data.diff()
# [NaN,1,1,1,1,1,1,5,1,1,1,3,1]

现在我想让所有的配对都围绕大于1的缺口

data[diffs > 1]将给我[12,18]

但是我真的想要

[6,7,12,13],
[14,15,18,19]

所以我可以轮班做事,但这似乎是错的,甚至根本不是解决方案

masked_around = ((diffs > 1)| (diffs.shift(-1) > 1) | (diffs.shift(-2) > 1) | (diffs.shift(1) > 1))
data[masked_around]

基本上可以满足我的需要,但说给我data[match_index-3:match_index+1]

的方式似乎非常错误

1 个答案:

答案 0 :(得分:1)

一种可能的解决方案

idx=data.index[data.diff() > 1]

[data.iloc[x : min(y+1, data.index.max()+1)].tolist() for x , y in zip(idx-2, idx+1)]
Out[34]: [[6, 7, 12, 13], [14, 15, 18, 19]]