特定时间间隔的平均大熊猫数据帧时间索引

时间:2018-01-26 14:19:02

标签: python pandas dataframe

我有一个数据框,每个时间戳都有一些用户获得的积分。看起来如下,即几秒钟后收集数据

>> df.head()
                     points
timestamp                                                    
2017-05-29 17:40:45    5
2017-05-29 17:41:53    7
2017-05-29 17:42:34    3
2017-05-29 17:42:36    8 
2017-05-29 17:42:37    6

然后我想重新采样到5分钟,所以我做了这个

>> df.resample("5min").mean()
                points
timestamp   
5/29/2017 17:40   8
5/29/2017 17:45   1
5/29/2017 17:50   4
5/29/2017 17:55   3
5/29/2017 18:00   8
5/30/2017 17:30   3
5/30/2017 17:35   3
5/30/2017 17:40   7
5/30/2017 17:45   8
5/30/2017 17:50   5
5/30/2017 17:55   7
5/30/2017 18:00   1

现在我想给出一个像input_time = "17:00-18:00"这样的输入,我想把输入时间分成5分钟的间隔,例如[17:05, 17:10 ... 17:55, 18:00]。在此之后,我希望获得该特定时间间隔的平均积分。结果应如下所示

interval points
17:00     -
17:05     -
….  
17:30     3
17:35     3
17:40     7.5
17:45     4.5
17:50     4.5
17:55     5
18:00     4.5

需要你的帮助。感谢

1 个答案:

答案 0 :(得分:2)

date_range创建DatetimeIndex,然后按strftime更改格式:

input_time = "17:00-18:00"
s,e = input_time.split('-')
r = pd.date_range(s, e, freq='5T').strftime('%H:%M')
print (r)
['17:00' '17:05' '17:10' '17:15' '17:20' '17:25' '17:30' '17:35' '17:40'
 '17:45' '17:50' '17:55' '18:00']

同样将groupby的原始indexmean汇总range转换为df = df.groupby(df.index.strftime('%H:%M'))['points'].mean().reindex(r) print (df) 17:00 NaN 17:05 NaN 17:10 NaN 17:15 NaN 17:20 NaN 17:25 NaN 17:30 3.0 17:35 3.0 17:40 7.5 17:45 4.5 17:50 4.5 17:55 5.0 18:00 4.5 Name: points, dtype: float64 的最后reindex

{{1}}