首页 > 解决方案 > 如何在时间点计算 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

标签: pythonpandasdataframepandas-groupby

解决方案


使用GroupBy.countand 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

推荐阅读