Python 标记系列中连续的真元素组
我有一系列布尔值,我想标记连续的真值组。这怎么可能呢?是否有可能以矢量化的方式进行此操作?任何帮助都将不胜感激 数据:Python 标记系列中连续的真元素组,python,pandas,time-series,series,Python,Pandas,Time Series,Series,我有一系列布尔值,我想标记连续的真值组。这怎么可能呢?是否有可能以矢量化的方式进行此操作?任何帮助都将不胜感激 数据: A 0 False 1 True 2 True 3 True 4 False 5 False 6 True 7 False 8 False 9 True 10 True A Label 0 False 0 1 True 1 2 True 1 3
A
0 False
1 True
2 True
3 True
4 False
5 False
6 True
7 False
8 False
9 True
10 True
A Label
0 False 0
1 True 1
2 True 1
3 True 1
4 False 0
5 False 0
6 True 2
7 False 0
8 False 0
9 True 3
10 True 3
所需:
A
0 False
1 True
2 True
3 True
4 False
5 False
6 True
7 False
8 False
9 True
10 True
A Label
0 False 0
1 True 1
2 True 1
3 True 1
4 False 0
5 False 0
6 True 2
7 False 0
8 False 0
9 True 3
10 True 3
下面是一个不太可能但简单有效的解决方案:
import scipy.ndimage.measurements as mnts
labeled, clusters = mnts.label(df.A.values)
# labeled is what you want, cluster is the number of clusters.
df.Labels = labeled # puts it into df
测试为:
a = array([False, False, True, True, True, False, True, False, False,
True, False, True, True, True, True, True, True, True,
False, True], dtype=bool)
labeled, clusters = mnts.label(a)
>>> labeled
array([0, 0, 1, 1, 1, 0, 2, 0, 0, 3, 0, 4, 4, 4, 4, 4, 4, 4, 0, 5], dtype=int32)
>>> clusters
5
使用cumsum
您可以使用
cumsum
和groupby
+ngroup
标记组
v = (~df.A).cumsum().where(df.A).bfill()
df['Label'] = (
v.groupby(v).ngroup().add(1).where(df.A).fillna(0, downcast='infer'))
df
A Label
0 False 0
1 True 1
2 True 1
3 True 1
4 False 0
5 False 0
6 True 2
7 False 0
8 False 0
9 True 3
10 True 3
工作完美。非常感谢你!