Python 熊猫分组在分类系列中运行
给出了一个系列,如下所示:Python 熊猫分组在分类系列中运行,python,pandas,Python,Pandas,给出了一个系列,如下所示: 将numpy导入为np 作为pd进口熊猫 N=18 颜色=np.重复(列表(“ABCABC”),3) ss=pd.系列(颜色,索引=pd.日期范围(“2020-01-01”,周期=N, freq=“10s”,tz=“UTC”), dtype=“类别”) >>>印刷品(ss) 2020-01-01 00:00:00+00:00A 2020-01-01 00:00:10+00:00A 2020-01-01 00:00:20+00:00A 2020-01-01 00:00:
将numpy导入为np
作为pd进口熊猫
N=18
颜色=np.重复(列表(“ABCABC”),3)
ss=pd.系列(颜色,索引=pd.日期范围(“2020-01-01”,周期=N,
freq=“10s”,tz=“UTC”),
dtype=“类别”)
>>>印刷品(ss)
2020-01-01 00:00:00+00:00A
2020-01-01 00:00:10+00:00A
2020-01-01 00:00:20+00:00A
2020-01-01 00:00:30+00:00B
2020-01-01 00:00:40+00:00B
2020-01-01 00:00:50+00:00B
2020-01-01 00:01:00+00:00摄氏度
2020-01-01 00:01:10+00:00摄氏度
2020-01-01 00:01:20+00:00摄氏度
2020-01-01 00:01:30+00:00A
2020-01-01 00:01:40+00:00A
2020-01-01 00:01:50+00:00A
2020-01-01 00:02:00+00:00B
2020-01-01 00:02:10+00:00B
2020-01-01 00:02:20+00:00B
2020-01-01 00:02:30+00:00摄氏度
2020-01-01 00:02:40+00:00摄氏度
2020-01-01 00:02:50+00:00摄氏度
频率:10S,数据类型:类别
类别(3,对象):[A、B、C]
我如何将其分组,使类别连续级别的每个块都是自己的组?在本例中,这意味着最终有6个组。使用
shift
和cumsum
创建子键
m = ss.ne(ss.shift()).cumsum()
ss.groupby(m).ngroups
6
非常聪明!不知道有关
shift