【发布时间】:2018-10-30 09:17:33
【问题描述】:
如何将 pandas 字符串索引转换为日期时间格式
我的数据框'df'是这样的
value
2015-09-25 00:46 71.925000
2015-09-25 00:47 71.625000
2015-09-25 00:48 71.333333
2015-09-25 00:49 64.571429
2015-09-25 00:50 72.285714
但索引是字符串类型,但我需要它是日期时间格式,因为我收到错误
'Index' object has no attribute 'hour'
使用时
df['A'] = df.index.hour
【问题讨论】:
-
df.index.to_datetime()或df.index = pandas.to_datetime(df.index)(前者现已弃用)。 -
type(df.index[1]) 仍然返回 'str'
-
上面的数据转换为
datetime没有问题-type(df.index[1]) == pandas.tslib.Timestamp。其余数据框中是否有错误数据? -
您也可以指定格式和错误 kwag。
pandas.to_datetime的文档将解释其余部分。