【问题标题】:Resampling pandas dataframe to a day is removing the hour part将 pandas 数据帧重新采样到一天正在删除小时部分
【发布时间】:2016-06-20 09:13:13
【问题描述】:

我正在尝试将包含基于分钟的数据的大型数据集插入 Google BigQuery,但为了降低查询时的资源使用率,我使用 pandas 将数据重新采样到 4 个单独的 csv 文件中:分钟、15 分钟、小时和天。对于前 3 个,一切都重新采样就好了。但是当我尝试重新采样到日值时,重新采样函数会删除小时信息(我只需要在 00:00 获得)。

BigQuery 将时间戳格式指定为 YYYY-MM-DD HH:MM:SS,但我只有 YYYY-MM-DD 作为日期值。

代码如下:

for i, f in enumerate(fluksos):
print "Flukso {} of {}".format(i+1, len(fluksos))
for j, s in enumerate(f.sensors):
    print "Sensor {} of {}".format(j+1, len(f.sensors))
    for week in weekindex:
        print "week {}, fetching data".format(week),
        ts = dl.tmpo_series(s.sensor_id, head=week, tail= week + pd.Timedelta(days=7))
        if ts is None:
            print "No data"
            continue
        print "success"
        ts = pd.concat([ts], axis=1)
        ts.columns = ['consumption']

        ts = ts.resample('d', how='mean')
        ts['meterID'] = s.sensor_id

        for group in ts.groupby(ts.index.day):
            filename = "day.{}.{}.csv".format(s.sensor_id,group[1].first_valid_index().date())

            #save file locally
            group[1].to_csv('temp.csv', header=False)

            if os.path.isfile(os.path.join(path_to_data,filename)) and (filecmp.cmp('temp.csv', os.path.join(path_to_data, filename))):
                print "file already exists, not saving",
                continue
            else:
                print "saving new file",
            group[1].to_csv(os.path.join(path_to_data, filename), header=False)

            print ".",
        print "week done"

我知道我必须更改ts = ts.resample('d', how='mean') 行中的某些内容,但我似乎无法弄清楚是什么。请记住,我在 Python 编程方面没有太多经验。

编辑和修复:

我能够像这样解决问题:

ts = ts.tz_localize('UTC')
ts = ts.tz_convert('Europe/Brussels')
ts = ts.resample('d', how='mean')

显然我的数据框包含没有时区信息的时间戳,因此时间戳的小时部分被删除。因此,通过在重新采样之前添加时区,问题得到了解决

【问题讨论】:

  • 对通过搜索来到这里的人的一般评论。有时将1D 换成24H 会有所帮助。仅此更改可能无法解决此问题,但当我使用频率 >= 1D 时,它通过重新采样帮助我解决了一些问题。

标签: python date pandas timestamp resampling


【解决方案1】:

我能够像这样解决问题:

ts = ts.tz_localize('UTC')
ts = ts.tz_convert('Europe/Brussels')
ts = ts.resample('d', how='mean')

显然我的数据帧包含没有时区信息的时间戳,因此时间戳的小时部分被删除。因此,通过在重新采样之前添加时区,问题得到了解决

【讨论】:

    【解决方案2】:

    您确定您正在浪费时间,还是只是不显示?

    df = pd.DataFrame({'A': [1, 2, 3, 4, 5]}, index=pd.date_range('2016-1-1 23:00', freq='H', periods=5))
    
    df2 = df.resample('d')
    >>> df2 
                  A
    2016-01-01  1.0
    2016-01-02  3.5
    
    # Pandas 0.17.1
    >>> df2.index[0]
    Timestamp('2016-01-01 00:00:00', offset='D')
    

    如果你真的只有几天,你也可以这样做:

    df2.index = pd.to_datetime(df2.index + ' 00:00:00')
    

    【讨论】:

      猜你喜欢
      • 2017-09-19
      • 2018-08-26
      • 1970-01-01
      • 1970-01-01
      • 2023-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-04
      相关资源
      最近更新 更多