如何利用时间点计算大Pandas群体的累积计数?

2024-06-16 09:47:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个df,其中包含多张JIRA门票的每周快照。我想计算一下年初至今的票数。你知道吗

数据框如下所示:

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(),我可以得到每个snaphsots中的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票证的数量应该是2008-01-07+计数2008-01-01。你知道吗


Tags: 数据iddf数量countjira快照票证
3条回答

下面是一种用size转换并乘以在pointInTime上取pd.factorize的结果的方法:

df['cumCount'] = (df.groupby('pointInTime').ticketId
                    .transform('size')
                    .mul(pd.factorize(df.pointInTime)[0]+1))

 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

我正在使用value_counts

df.pointInTime.map(df.pointInTime.value_counts().sort_index().cumsum())
Out[207]: 
0    3
1    3
2    3
3    6
4    6
5    6
6    9
7    9
8    9
Name: pointInTime, dtype: int64

或者

pd.Series(np.arange(len(df))+1,index=df.index).groupby(df['pointInTime']).transform('last')
Out[216]: 
0    3
1    3
2    3
3    6
4    6
5    6
6    9
7    9
8    9
dtype: int32

使用^{}^{},然后^{}将结果返回到“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

相关问题 更多 >