获取 Pandas 中字符串的开始和结束索引

Getting start and end indices of string in Pandas

我有一个看起来像这样的 df:

|Index|Value|Anomaly|
---------------------
|0    |4    |       |
|1    |2    |Anomaly|
|2    |1    |Anomaly|
|3    |2    |       |
|4    |6    |Anomaly|

我想获取连续异常计数的开始和结束索引,因此在这种情况下,它将是 [[1,2],[4]]

我知道我必须使用 .shift.cumsum 但是我迷路了,我希望有人能够启发我。

获取布尔系列的累积和的连续组,检查值不是 'Anomoly' 的地方。使用 where 以便我们只获取 'Anomoly' 行。然后我们可以遍历组并获取索引。

m = df['Anomaly'].ne('Anomaly')

[[idx[0], idx[-1]] if len(idx) > 1 else [idx[0]] 
 for idx in df.groupby(m.cumsum().where(~m)).groups.values()]
#[[1, 2], [4]]

或者,如果您想使用更长的时间 groupby,您可以获取第一个和最后一个索引,然后删除重复项(以处理只有 1 个的条纹)并将其放入列表列表中。不过这要慢得多

(df.reset_index().groupby(m.cumsum().where(~m))['index'].agg(['first', 'last'])
   .stack()
   .drop_duplicates()
   .groupby(level=0).agg(list)
   .tolist())
#[[1, 2], [4]]