熊猫时间序列重新采样+线性调整值

问题描述

如何使用python和pandas将时间序列重新采样为均匀的5分钟间隔(偏移量为整小时的零分钟),同时还可以线性调整值?

因此,我想打开它:

         value
00:01    2
00:05    10
00:11    22
00:14    28

对此:

         value
00:00    0
00:05    10
00:10    20
00:15    30

请注意如何调整“值”列。

  • 为简单起见,我选择的值正好是2 *分钟数。
  • 但是,在现实生活中,这些价值并不是那么完美。有时在两个偶数5分钟间隔之间将存在一个以上的值,有时在两个“真实”值之间存在一个以上5分钟的间隔,因此在重采样时,我需要针对每个偶数5分钟的间隔找到“真实”值”(即使间隔为5分钟)之前和之后的值,并根据它们计算线性插值。

PS。

在互联网上到处都有关于此的很多信息,但是我仍然找不到能够完成我想要做功能(求和,最大值,均值等,或者编写我自己的functino)

解决方法

我已经重新考虑了代码,因为注释中省略了该要求。通过将原始数据帧与延长到一分钟的数据帧组合来创建新的数据帧。我线性插入新数据帧,并以5分钟为增量提取结果。这是我对过程的理解。如果我错了,请给我另一个答案。

import pandas as pd
import numpy as np
import io

data = '''
time value
00:01 2
00:05 10
00:11 22
00:14 28
00:18 39
'''
df = pd.read_csv(io.StringIO(data),sep='\s+')
df['time'] = pd.to_datetime(df['time'],format='%H:%M')
time_rng = pd.date_range(df['time'][0],df['time'][4],freq='1min')
df2 = pd.DataFrame({'time':time_rng})
df2 = df2.merge(df,on='time',how='outer')
df2 = df2.set_index('time').interpolate('time')
df2.asfreq('5min')
    value
time    
1900-01-01 00:01:00 2.0
1900-01-01 00:06:00 12.0
1900-01-01 00:11:00 22.0
1900-01-01 00:16:00 33.5
,

您可以使用日期时间和时间模块获取时间间隔的顺序。然后使用熊猫将字典转换为数据框。这是执行此操作的代码。

import time,datetime
import pandas as pd

#set the dictionary as time and value
data = {'Time':[],'Value':[]}

#set a to 00:00 (HH:MM) 
a = datetime.datetime(1,1,0)

#loop through the code to create 60 mins. You can increase loop if you want more values
#skip by 5 to get your 5 minute interval

for i in range (0,61,5):
    # add the time and value into the dictionary
    data['Time'].append(a.strftime('%H:%M'))
    data['Value'].append(i*2)

    #add 5 minutes to your date-time variable

    a += datetime.timedelta(minutes=5)

#now that you have all the values in dictionary 'data',convert to DataFrame
df = pd.DataFrame.from_dict(data)

#print the dataframe
print (df)

#for your reference,I also printed the dictionary
print (data)

字典将如下所示:

{'Time': ['00:00','00:05','00:10','00:15','00:20','00:25','00:30','00:35','00:40','00:45','00:50','00:55','01:00'],'Value': [0,10,20,30,40,50,60,70,80,90,100,110,120]}

数据框如下所示:

     Time  Value
0   00:00      0
1   00:05     10
2   00:10     20
3   00:15     30
4   00:20     40
5   00:25     50
6   00:30     60
7   00:35     70
8   00:40     80
9   00:45     90
10  00:50    100
11  00:55    110
12  01:00    120