【问题标题】:Pandas groupby month and year (date as datetime64[ns]) and summarized by countPandas 按月和年分组(日期为 datetime64[ns])并按计数汇总
【发布时间】:2020-05-18 21:18:26
【问题描述】:

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

【问题讨论】:

    标签: python pandas pandas-groupby python-datetime


    【解决方案1】:

    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')
    

    【讨论】:

    • @Ben.T 如果您需要一个灵活的函数来允许不同的聚合,那就太好了。例如,很容易将上面的内容更改为聚合到 Year、Y-Quarter、Y-M 组(字面意思是更改为 Y、Q、M),而不是调用所有属性。基本上它是resample,但并没有给你所有的NaN 组。
    • 可以添加 strftime 吗?
    【解决方案2】:

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

    【讨论】:

    • 完美!国王!非常感谢!
    • 我会接受你的回答,因为你是第一个:)。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    相关资源
    最近更新 更多