Data:
0 09:30:38
1 13:40:27
2 18:05:24
3 04:58:08
4 09:00:09
Essentially what I'd like to do is split this into three columns [hour, minute, second]
I've tried the following code but none seem to be working:
train_sample.time.hour
AttributeError: 'Series' object has no attribute 'hour'train_sample.time.dt.hour
AttributeError: Can only use .dt accessor with datetimelike values pd.DatetimeIndex(train_sample.time).hour
TypeError: <class 'datetime.time'> is not convertible to datetime
This seems so simple but I can't figure it out. Any help would be much appreciated.
Use list comprehension with extract attributes of time
s:
import datetime as datetimedf = pd.DataFrame({'time': [datetime.time(9, 30, 38), datetime.time(13, 40, 27), datetime.time(18, 5, 24),datetime.time(4, 58, 8), datetime.time(9, 0, 9)]})print (df)time
0 09:30:38
1 13:40:27
2 18:05:24
3 04:58:08
4 09:00:09df[['h','m','s']] = pd.DataFrame([(x.hour, x.minute, x.second) for x in df['time']])
Or convert to string
s, split and convert to int
:
df[['h','m','s']] = df['time'].astype(str).str.split(':', expand=True).astype(int)print (df)time h m s
0 09:30:38 9 30 38
1 13:40:27 13 40 27
2 18:05:24 18 5 24
3 04:58:08 4 58 8
4 09:00:09 9 0 9