【问题标题】:pandas dataframe resample per day without date time index熊猫数据框每天重新采样,没有日期时间索引
【发布时间】:2016-10-16 23:18:54
【问题描述】:

我有一个如下形式的熊猫数据框:

      timestamps         light
7   2004-02-28 00:58:45 150.88
26  2004-02-28 00:59:45 143.52
34  2004-02-28 01:00:45 150.88
42  2004-02-28 01:01:15 150.88
59  2004-02-28 01:02:15 150.88

这里注意索引不是时间戳列。但我想重新采样(或以某种方式对数据进行分类)以反映每分钟、每小时、每天等光柱的平均值。我研究了 pandas 提供的resample 方法,它要求数据框有一个该方法工作的数据时间索引(除非我误解了这一点)。

  1. 所以我的第一个问题是,我可以重新索引数据帧以将时间戳作为索引(请注意,并非每一行都有唯一的时间戳,对于每个时间戳,大约有 30 行具有相同的时间戳,每个代表一个传感器)。

  2. 如果没有,是否有其他方法可以实现另一个数据帧,该数据帧具有每小时、每天、每月等的平均值?

任何帮助将不胜感激。

【问题讨论】:

    标签: python pandas dataframe time-series


    【解决方案1】:

    你是对的 - 需要 DatetimeIndexTimedeltaIndexPeriodIndex 否则错误:

    TypeError:仅对 DatetimeIndex、TimedeltaIndex 或 PeriodIndex 有效,但获得了 'Index' 的实例

    因此,如果原始index 很重要,您必须首先使用reset_indexset_index

    print (df.reset_index().set_index('timestamps'))
                         index   light
    timestamps                        
    2004-02-28 00:58:45      7  150.88
    2004-02-28 00:59:45     26  143.52
    2004-02-28 01:00:45     34  150.88
    2004-02-28 01:01:15     42  150.88
    2004-02-28 01:02:15     59  150.88
    

    如果不只是set_index:

    print (df.set_index('timestamps'))
                          light
    timestamps                 
    2004-02-28 00:58:45  150.88
    2004-02-28 00:59:45  143.52
    2004-02-28 01:00:45  150.88
    2004-02-28 01:01:15  150.88
    2004-02-28 01:02:15  150.88
    

    然后resample:

    print (df.reset_index().set_index('timestamps').resample('1D').mean())
                index    light
    timestamps                
    2004-02-28   33.6  149.408
    

    【讨论】:

      【解决方案2】:

      对于 pandas 0.19.0 及更高版本,您可以使用 on 关键字:

      df.resample('H', on='timestamps').mean()
      

      结果:

                            light
      timestamps                 
      2004-02-28 00:00:00  147.20
      2004-02-28 01:00:00  150.88
      

      【讨论】:

        【解决方案3】:

        这是一种重新采样的方法

        您可以使用以下方法以T 间隔进行采样。

        如果原始数据在每个minute 中,您的新重新采样数据将在2 min 间隔。 您可以使用 3T, 4T.... 任何适合您需要的 T 值。

        df_2T = df.resample('2T', on = 'timestamp').mean()

        每小时 df_hourly = df.resample('60T', on = 'timestamp').mean()

        每日 df_daily = df.resample('1440T', on = 'timestamp').mean()

        注意:一天有 60*24 = 1440 分钟

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-06-08
          • 1970-01-01
          • 2017-06-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多