首页 > 解决方案 > 计算一个计数器在 groupby 中递增的次数

问题描述

我有一个熊猫数据框,如下所示:

df = pd.DataFrame(data={'id':[1234, 1234, 1234, 1234, 1234], 'year':['2017', '2017', '2018', '2018', '2018'], 'count_to_today':[1, 2, 3, 3, 4})

count_to_today我需要计算每年每年累计发生多少次id。IE

counts = pd.DataFrame(data={'id':[1234, 1234, 1234, 1234, 1234], 'year':['2017', '2017', '2018', '2018', '2018'], 'count_to_today':[1, 2, 1, 1, 2]})

即我从一开始就有一个运行计数,我想计算它每年累积增加的次数。

我对如何做到这一点有点困惑。我知道我需要分组idyear但我不知道如何获得.count().value_counts()给我每年的计数。

标签: pythonpandas

解决方案


与您之前的问题类似,但请cumsum改用:

df.count_to_today.diff().ne(0).groupby([df.id, df.year]).cumsum()

0    1.0
1    2.0
2    1.0
3    1.0
4    2.0
Name: count_to_today, dtype: float64

df['count_to_today'] = (
    df.count_to_today.diff().ne(0).groupby([df.id, df.year]).cumsum().astype(int))
df

     id  year  count_to_today
0  1234  2017               1
1  1234  2017               2
2  1234  2018               1
3  1234  2018               1
4  1234  2018               2

推荐阅读