连续True间隔的开始和结束索引

时间:2018-07-22 01:16:09

标签: python pandas series

我有以下熊猫系列:

s = pd.Series([False, True, True, False, True, True, True, False, True])

我如何获得一个元组列表,每个元组代表连续的True间隔的开始和结束索引。对于上述摘要,预期结果将是:

[(1, 2), (4, 6), (8, 8)]

1 个答案:

答案 0 :(得分:1)

IIUC

t=s[s].index.to_series()
t.groupby(t.diff().ne(1).cumsum()).agg(['first','last']).apply(tuple,1).tolist()
Out[257]: [(1, 2), (4, 6), (8, 8)]