【问题标题】:Groupby and sum datetime64 dates by several days of a weekend in pandasGroupby 和 sum datetime64 在 pandas 中按周末的几天约会
【发布时间】:2020-09-08 08:36:05
【问题描述】:

我看到了多个数据按星期几分组的问题,但我没有找到任何数据按几天分组的问题。

我有一个数据集

   date    day_type     bus  rail_boardings  total_rides
6636 2019-01-01        U  248879          245852       494731
6637 2019-01-02        W  591006          573542      1164548
6638 2019-01-03        W  664442          627781      1292223
6639 2019-01-04        W  668812          628514      1297326
6640 2019-01-05        A  444434          348257       792691

如您所见,我有 day_type,其中 W = 工作日,A = 星期六,U = 星期日/节假日。

我想使用 pandas 和 matplotlib 显示特定周末(周五/周六/周日)没有节假日的活动下降,并可视化为时间序列。它将允许我比较 2019 年和 2020 年之间周末的活动。星期六日期可以是日期列中的日期(或星期五,或星期日,无所谓)。

理想输出:

date                day_type   bus      rail_boardings  total_rides
6636 2019-01-01        Weekend 1  248879          245852       494731
6637 2019-01-07        Weekend 2  591006          573542      1164548
6638 2019-01-14        Weekend 3  664442          627781      1292223

欣赏任何想法!

【问题讨论】:

    标签: python pandas datetime pandas-groupby


    【解决方案1】:

    你在这里问的是一个定制的解决方案,尤其是。按周六和周日的分类在不同的垃圾箱中,比如

    df= pd.DataFrame({'date': pd.date_range('2018-01-01', periods=50, freq='d'), 'value':[1]*50})
    map_days = {
        6: 'A',
        5: 'U',
        4: 'W',
        3: 'W',
        2: 'W',
        1: 'W',
        0: 'W'}
    df=df.assign(grouper=lambda x:x['date'].dt.weekday.map(map_days))
    df.groupby('grouper')['value'].count()
    

    否则,您也可以使用 pandas buildin 工作日,请参阅 https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-custombusinessdays,但您总是会得到二进制分类。

    【讨论】:

    • 非常感谢您抽出宝贵时间!第一个解决方案不是我想要的,但感谢第二个提示!会检查的。
    猜你喜欢
    • 2019-09-29
    • 2017-03-16
    • 2016-12-23
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多