python - 如何在时间点计算 Pandas 中的累积 groupby 计数?
问题描述
我有一个包含 JIRA 票证的多个每周快照的 df。我想计算年初至今的票数。
df 看起来像这样:
pointInTime ticketId
2008-01-01 111
2008-01-01 222
2008-01-01 333
2008-01-07 444
2008-01-07 555
2008-01-07 666
2008-01-14 777
2008-01-14 888
2008-01-14 999
所以如果我df.groupby(['pointInTime'])['ticketId'].count()
能得到每个快照中的 ID 计数。但我想要实现的是计算累积和。
并有一个 df 看起来像这样:
pointInTime ticketId cumCount
2008-01-01 111 3
2008-01-01 222 3
2008-01-01 333 3
2008-01-07 444 6
2008-01-07 555 6
2008-01-07 666 6
2008-01-14 777 9
2008-01-14 888 9
2008-01-14 999 9
所以2008-01-07
票的数量将是 count of 2008-01-07
+ count of 2008-01-01
。
解决方案
使用GroupBy.count
and cumsum
,然后map
将结果返回到“pointInTime”:
df['cumCount'] = (
df['pointInTime'].map(df.groupby('pointInTime')['ticketId'].count().cumsum()))
df
pointInTime ticketId cumCount
0 2008-01-01 111 3
1 2008-01-01 222 3
2 2008-01-01 333 3
3 2008-01-07 444 6
4 2008-01-07 555 6
5 2008-01-07 666 6
6 2008-01-14 777 9
7 2008-01-14 888 9
8 2008-01-14 999 9
推荐阅读
- javascript - 删除父 div 留下其子 div
- python - 如何将新词分类成亲和传播簇?
- vue.js - 如何使用 Vue.js 和 Nuxt 保护数据?
- google-sheets - Google Query Language 将不会显示位于单元格中提供的两个日期之间的范围
- r - 如何更改列表中数据框的列名
- php - Symfony - 在控制器中使用发布数据重定向
- javascript - 带有非拉丁字体的 jsPDF
- android - RecyclerView/Adapter 中的 TimePicker 使屏幕变暗
- bash - Bash:如果字符不存在,如何在行尾添加字符?
- sql - 根据季度查找所有记录