Skip to main content
 首页 » 编程设计

python之如何将以小时(h)为索引单位的 Pandas 时间序列转换为 Pandas 日期时间格式

2024年11月24日9bonelee

我正在处理时间序列数据,其中我的 pandas 数据框具有以小时为单位指定的索引,如下所示:

[0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4, ...] 

这会持续几千个小时。我知道第一次测量是在比方说 2017 年 5 月 1 日 12:00 进行的。我如何使用这些信息将我的索引转换为 pandas 日期时间格式?

请您参考如下方法:

您可以在 to_datetime 中通过参数 origin 将小时数添加到索引中对于 DatetimeIndex:

idx = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4] 
df = pd.DataFrame({'a':range(13)}, index=idx) 
 
start = 'May 1, 2017 12:00' 
df.index = pd.to_datetime(df.index, origin=start, unit='h') 
print (df) 
                      a 
2017-05-01 12:00:00   0 
2017-05-01 12:12:00   1 
2017-05-01 12:24:00   2 
2017-05-01 12:36:00   3 
2017-05-01 12:48:00   4 
2017-05-01 13:00:00   5 
2017-05-01 13:12:00   6 
2017-05-01 13:24:00   7 
2017-05-01 13:36:00   8 
2017-05-01 13:48:00   9 
2017-05-01 14:00:00  10 
2017-05-01 14:12:00  11 
2017-05-01 14:24:00  12