Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add hour to pandas dataframe column

I have a pandas dataframe time column like following.

 segments_data['time']
 Out[1585]: 
 0      04:50:00
 1      04:50:00
 2      05:00:00
 3      05:12:00
 4      06:04:00
 5      06:44:00
 6      06:44:00
 7      06:47:00
 8      06:47:00
 9      06:47:00

I want to add 5 hours and 30 mins to above time column. I am doing following in python.

pd.DatetimeIndex(segments_data['time']) + pd.DateOffset(hours=5,minutes=30)

But it gives me an error.

TypeError: object of type 'datetime.time' has no len()

please help.

like image 970
Neil Avatar asked Jan 27 '16 08:01

Neil


3 Answers

as of '0.25.3' this is as simple as

df[column] = df[column] + pd.Timedelta(hours=1)
like image 169
Tom Wattley Avatar answered Oct 25 '22 12:10

Tom Wattley


You can try importing timedelta:

from datetime import datetime, timedelta

and then:

segments_data['time'] = pd.DatetimeIndex(segments_data['time']) + timedelta(hours=5,minutes=30)
like image 40
Fabio Lamanna Avatar answered Oct 25 '22 13:10

Fabio Lamanna


Pandas does not support vectorised operations with datetime.time objects. For efficient, vectorised operations, there is no requirement to use the datetime module from the standard library.

You have a couple of options to vectorise your calculation. Either use a Pandas timedelta series, if your times represent a duration. Or use a Pandas datetime series, if your times represent specific points in time.

The choice depends entirely on what your data represents.

timedelta series

df['time'] = pd.to_timedelta(df['time'].astype(str)) + pd.to_timedelta('05:30:00')

print(df['time'].head())

0   10:20:00
1   10:20:00
2   10:30:00
3   10:42:00
4   11:34:00
Name: 1, dtype: timedelta64[ns]

datetime series

df['time'] = pd.to_datetime(df['time'].astype(str)) + pd.DateOffset(hours=5, minutes=30)

print(df['time'].head())

0   2018-12-24 10:20:00
1   2018-12-24 10:20:00
2   2018-12-24 10:30:00
3   2018-12-24 10:42:00
4   2018-12-24 11:34:00
Name: 1, dtype: datetime64[ns]

Notice by default the current date is assumed.

like image 37
jpp Avatar answered Oct 25 '22 13:10

jpp