How to extract hour, minute and second from Series filled with datetime.time values

假如想象 提交于 2019-12-06 02:43:01

问题


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.


回答1:


Use list comprehension with extract attributes of times:

import datetime as datetime

df = 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:09

df[['h','m','s']] = pd.DataFrame([(x.hour, x.minute, x.second) for x in df['time']])

Or convert to strings, 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



回答2:


Splitting using : and creating a dataframe with each of the split as separate column values.

import pandas as pd

d = {0: '09:30:38', 
     1: '13:40:27', 
     2: '18:05:24',
     3: '04:58:08',
     4: '09:00:09'}

df = pd.DataFrame([v.split(':') for v in d.values()], columns=['hour', 'minute', 'second'])
print(df)

Result:

  hour minute second
0   09     30     38                                        
1   13     40     27                                        
2   18     05     24                                        
3   04     58     08                                        
4   09     00     09      



回答3:


One way is to convert to timedelta and extract via pd.Series.dt.components:

df[['hour','minute','second']] = pd.to_timedelta(df['time']).dt.components.iloc[:, 1:4]

Result

       time  hour  minute  second
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


来源:https://stackoverflow.com/questions/49298488/how-to-extract-hour-minute-and-second-from-series-filled-with-datetime-time-val

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!