python - 如何从充满 datetime.time 值的系列中提取小时、分钟和秒

标签 python pandas datetime series

数据:

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

基本上我想做的是将其分成三列[小时、分钟、秒]

我已经尝试了以下代码,但似乎都不起作用:

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

这看起来很简单,但我想不通。任何帮助将非常感激。

最佳答案

将列表理解与 time 的提取属性结合使用:

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,拆分转为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

关于python - 如何从充满 datetime.time 值的系列中提取小时、分钟和秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49298488/

相关文章:

python - tensorflow 2.x : Cannot save trained model in h5 format (OSError: Unable to create link (name already exists))

python - 点、空格和换行符的正则表达式

python - 如何计算靠近点x,y的网格框的中心点?

python - 如何使用自定义 IO 函数扩展 Pandas?

python - 划分两个 pandas DataFrames 并保留非数字列

php - 获取本月的最后一天?

python - 我如何使用 python 2.6 安装 zope 接口(interface)?

python - pandas.factorize 整个数据框

ios - ios-ntp框架同步问题

python - 如何检查日期时间对象是否使用 pytz 本地化?