如何从填充有datetime.time值的系列中提取小时,分钟和秒 [英] How to extract hour, minute and second from Series filled with datetime.time values
本文介绍了如何从填充有datetime.time值的系列中提取小时,分钟和秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
数据:
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.
推荐答案
使用列表理解和time
s的提取属性:
Use list comprehension with extract attributes of time
s:
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']])
或转换为string
s,拆分并转换为int
:
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
这篇关于如何从填充有datetime.time值的系列中提取小时,分钟和秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文