熊猫将小时索引整数转换为日期时间

时间:2018-09-24 06:48:42

标签: python pandas datetime

我有一个这样的Pandas数据框:

   Date    Hour Actual      
2018-06-01  0   0.000000
2018-06-01  1   0.012000
2018-06-01  2   0.065000
2018-06-01  3   0.560000
...

我想转换这些Hour整数索引并添加到​​日期,以便它是Pandas的datetime对象。 结果应该是这样的:

       Date            Actual       
2018-06-01 00:00:00   0.000000
2018-06-01 01:00:00   0.012000
2018-06-01 02:00:00   0.065000
2018-06-01 03:00:00   0.560000
...

什么是有效的方法?熊猫是否提供将整数索引转换为日期时间对象的功能?

1 个答案:

答案 0 :(得分:4)

to_datetimeto_timedeltapop一起用于提取列time

df['Date'] = pd.to_datetime(df['Date']) + pd.to_timedelta(df.pop('Hour'), unit='H')
print (df)
                 Date  Actual
0 2018-06-01 00:00:00   0.000
1 2018-06-01 01:00:00   0.012
2 2018-06-01 02:00:00   0.065
3 2018-06-01 03:00:00   0.560
相关问题