Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas Combined Date and Hour Into One Column

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
like image 928
Jarad Avatar asked Dec 18 '22 17:12

Jarad


2 Answers

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]
like image 124
Alexander Avatar answered Dec 21 '22 10:12

Alexander


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
like image 23
Nathan Clement Avatar answered Dec 21 '22 09:12

Nathan Clement