Pandas按月和年分组(日期为datetime64[ns])并按计数汇总

6 投票
2 回答
9428 浏览
提问于 2025-06-18 04:06

我有一个数据框,这是我在pandas中创建的,按日期分组并总结骑行次数。

      date   rides
0   2019-01-01  247279
1   2019-01-02  585996
2   2019-01-03  660631
3   2019-01-04  662011
4   2019-01-05  440848
..         ...     ...
451 2020-03-27  218499
452 2020-03-28  143305
453 2020-03-29  110833
454 2020-03-30  207743
455 2020-03-31  199623

[456 rows x 2 columns]

我的date列是datetime64[ns]格式。

date     datetime64[ns]
rides             int64
dtype: object

现在我想创建另一个数据框,按月份和年份分组(我有2019年和2020年的数据),并总结骑行次数。

理想的输出结果是:

Year Month   Rides
2019 January 2000000
2020 March   1000000

相关问题:

  • 暂无相关问题
暂无标签

2 个回答

6

datetime 也支持 to_period 这个转换功能,这样我们就可以按月来对数据进行分组。

df.groupby(df.date.dt.to_period('M')).agg('sum')
#           rides
#date            
#2019-01  2596765
#2020-03   880003

在这种情况下,索引是一个 PeriodIndex,它有很多和 datetime 相似的属性。

PeriodIndex(['2019-01', '2020-03'], dtype='period[M]', name='date', freq='M')
11

你可以使用 groupby 来对数据进行分组,然后从日期这一列中提取出年份和月份的名字,分别用 dt.yeardt.month_name 来获取。

print (df.groupby([df['date'].dt.year.rename('year'), 
                   df['date'].dt.month_name().rename('month')])
         ['rides'].sum().reset_index())
   year    month    rides
0  2019  January  2596765
1  2020    March   880003

撰写回答