考虑以下因素
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]
所以我可以用shift来做事情,但这似乎是错误的,它基本上甚至不是一个解决方案
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]
最佳答案
潜在的解决方案之一
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]]
关于python - Pandas 在 bool 索引匹配周围获取 N 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57916178/