How would I combine Day
(datetime64[ns]) and Hour
(int64) into one datetime column?
Day Hour
0 2010-04-24 17
1 2012-08-20 10
2 2016-03-06 9
3 2016-01-02 10
4 2010-12-21 4
df = pd.DataFrame({
'Day': np.array(['2010-04-24', '2012-08-20', '2016-03-06', '2016-01-02', '2010-12-21'], dtype=np.datetime64),
'Hour': np.array([17, 10, 9, 10, 4], dtype=np.int64)})
>>> pd.to_datetime(df.Day) + pd.to_timedelta(df.Hour, unit='h')
0 2010-04-24 17:00:00
1 2012-08-20 10:00:00
2 2016-03-06 09:00:00
3 2016-01-02 10:00:00
4 2010-12-21 04:00:00
dtype: datetime64[ns]
Use this list comprehension to create a column that adds Hour to Day using dt.timedelta:
data = {'Day':pd.to_datetime(['2010-04-24','2012-08-20','2016-03-06','2016-01-02','2010-12-21']),'Hour':[17,10,9,10,4]}
df = pd.DataFrame(data)
df['Datetime'] = [df.loc[x,'Day'] + dt.timedelta(hours = int(df.loc[x,'Hour'])) for x in list(df.index)]
This assumes that the hours/minutes/seconds of the Day column are all 00:00:00
Returns
Day Hour Datetime
2010-04-24 17 2010-04-24 17:00:00
2012-08-20 10 2012-08-20 10:00:00
2016-03-06 9 2016-03-06 09:00:00
2016-01-02 10 2016-01-02 10:00:00
2010-12-21 4 2010-12-21 04:00:00
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With