我想为每个"ID“中的"Button”列(Start,Stop)中的值创建一个运行计数。但是,"Button“值的任何更改或"ID”的更改都应重置运行计数。数据框如下:
data = pd.DataFrame({
'ID': ['A','A','B','B','C','C','C','C','C','D','E','E'],
'Button': ['Start','Stop','Start','Stop','Start','Start','Stop','Start','Stop','Start','Start','Stop']
})
我可以根据"Button“值创建一个运行计数,但不知道如何按"ID”分组。
data['runningCount'] = data.groupby(data['Button']).cumcount()+1
我正在寻找以下结果:
result = pd.DataFrame({
'ID': ['A','A','B','B','C','C','C','C','C','D','E','E'],
'Button': ['Start','Stop','Start','Stop','Start','Start','Stop','Start','Stop','Start','Start','Stop'],
'Count': [1,1,1,1,1,2,1,1,1,1,1,1]})
发布于 2018-06-26 09:03:41
您只需要使用shift
创建一个特定的密钥
s=data.groupby('ID').Button.apply(lambda x : (x!=x.shift()).cumsum())
data.groupby([data.ID,s]).cumcount()+1
Out[189]:
0 1
1 1
2 1
3 1
4 1
5 2
6 1
7 1
8 1
9 1
10 1
11 1
dtype: int64
更多信息
data.groupby('ID').Button.apply(lambda x : (x!=x.shift()).cumsum())
Out[192]:
0 1
1 2
2 1
3 2
4 1
5 1
6 2
7 3
8 4
9 1
10 1
11 2
Name: Button, dtype: int32
https://stackoverflow.com/questions/51033454
复制相似问题