Python 计算groupby中每年发生的事件数

Python 计算groupby中每年发生的事件数,python,pandas,Python,Pandas,我有一个熊猫数据框,看起来像: df = pd.DataFrame(data={'id':[1234, 1234, 1234, 1234, 1234], 'year':['2017', '2017', '2018', '2018', '2018'], 'count_to_today':[1, 2, 3, 3, 4]}) df id year count_to_today 0 1234 2017 1 1 1234 2017

我有一个熊猫数据框,看起来像:

df = pd.DataFrame(data={'id':[1234, 1234, 1234, 1234, 1234], 'year':['2017', '2017', '2018', '2018', '2018'], 'count_to_today':[1, 2, 3, 3, 4]})
df
     id  year  count_to_today
0  1234  2017               1
1  1234  2017               2
2  1234  2018               3
3  1234  2018               3
4  1234  2018               4
我需要计算每个
id
每年发生多少次
count\u to\u today
。i、 e.我有一个从时间开始的连续计数,我想计算它每年递增的次数。

           count_in_year
id   year               
1234 2017              2
     2018              2

我对怎么做有点困惑。我知道我需要按
id
year
分组,但我不知道如何获取
.count()
.value\u counts()
来给我每年的计数。

你可以使用
diff
分组:

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

id    year
1234  2017    2.0
      2018    2.0
Name: count_to_today, dtype: float64


如果你想每年统计一次身份证 试用-

df[['ID','Year']].groupby('Year').count()

根据需要更改变量以获得结果。

使用以下结构:

df[['ID','Year']].groupby('Year').count()


我希望这能起到很好的作用。试试这个

伙计们,“我想计算it每年增加的次数。”这并没有解决问题中“我想计算it每年增加的次数”的部分。。。
df[['ID','Year']].groupby('Year').agg('count')
df[['ID','Year']].groupby('Year').count()
df[['ID','Year']].groupby('Year').agg('count')