首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >pandas -基于多列的运行计数

pandas -基于多列的运行计数
EN

Stack Overflow用户
提问于 2018-06-26 08:42:10
回答 1查看 619关注 0票数 3

我想为每个"ID“中的"Button”列(Start,Stop)中的值创建一个运行计数。但是,"Button“值的任何更改或"ID”的更改都应重置运行计数。数据框如下:

代码语言:javascript
复制
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”分组。

代码语言:javascript
复制
data['runningCount'] = data.groupby(data['Button']).cumcount()+1

我正在寻找以下结果:

代码语言:javascript
复制
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]})
EN

回答 1

Stack Overflow用户

发布于 2018-06-26 09:03:41

您只需要使用shift创建一个特定的密钥

代码语言:javascript
复制
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

更多信息

代码语言:javascript
复制
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
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51033454

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档