【问题标题】:Aggregate and plot time series in pandas在 pandas 中聚合和绘制时间序列
【发布时间】:2022-01-23 13:29:17
【问题描述】:

我有一个以日期为索引的数据框。我想计算每两周汇总一次的事件并进行绘图。示例:

date        id
2018-01-01  a1
2018-01-01  a2
2018-01-05  a3
2018-01-12  a4
2018-01-15  a5
2018-01-17  a6
2018-01-19  a7
...

应该显示为(格式是说明性的,如果我能够区分就可以了):

2018-01-1   4
2018-01-2   3
...

然后绘制。

如果可能,我想要一个参数,以便我能够切换到每周或每月。

【问题讨论】:

    标签: python pandas date plot time-series


    【解决方案1】:

    如果日期是索引,您可以将 resample 与 SemiMonthStart ('SMS') 频率一起使用:

    df.index = pd.to_datetime(df.index)
    df.resample('SMS').count()
    

    输出:

                id
    date          
    2018-01-01   4
    2018-01-15   3
    

    您也可以使用date offsets (here SemiMonthBegin) 对日期进行四舍五入,并将此结果用于groupby+count

    group = (pd.to_datetime(df['date'])
               .apply(pd.offsets.SemiMonthBegin().rollback)
               )
    
    out = df.groupby(group)['id'].count()
    

    输出:

    date
    2018-01-01    4
    2018-01-15    3
    Name: id, dtype: int64
    

    【讨论】:

      猜你喜欢
      • 2016-07-21
      • 1970-01-01
      • 2019-08-09
      • 2021-04-17
      • 1970-01-01
      • 2016-05-07
      • 2016-11-29
      • 2018-05-18
      • 2015-05-28
      相关资源
      最近更新 更多