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

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

This question already has an answer here:
Creating 2D numpy array of start and end indices of “streaks” in another array.
                                
                                    (1个答案)
                                
                        
                                2年前关闭。
            
                    
我有以下熊猫系列:

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


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

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

最佳答案

联合会

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)]

关于python - 连续的True间隔的开始和结束索引,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51461280/

10-09 17:12