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

标签 python pandas pandas-groupby python-datetime

我有一个数据框,它是在 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

最佳答案

您可以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

关于python - Pandas 按月和年分组(日期为 datetime64[ns])并按计数汇总,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61879166/

相关文章:

python - 无法在 Python Pandas 中添加多个包含值的列

python - 基于多列的唯一值

python - Pandas:如何使用 groupby 和 apply() 标记列

python - Pandas : Data Frame Pruning

python - Pandas 从特定日期和时间范围读取 csv 数据帧行

python - 计算仅在 B 列和/或 C 列中观察到的单个不同值的 A 列值

python - 一张图片上的多个图表(python)

python - 将行数据移动到列(不转置)

python - 我可以向量化这个Python代码吗?

python - 我可以将值列表设置为字典中的键列表吗?