Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas convert Hour index integer to datetime

i have a Pandas dataframe like this:

   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
...

I want to convert these Hour integer indexes and add to date so that it is a Pandas' datetime object. The result should be like this:

       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
...

What would be an efficient way to do that? Does Panda provide functionality for converting integer indexes into datetime objects?

like image 887
Osama Arshad Dar Avatar asked Dec 22 '25 03:12

Osama Arshad Dar


1 Answers

Use to_datetime with to_timedelta and pop for extract column 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
like image 118
jezrael Avatar answered Dec 23 '25 15:12

jezrael