python可以将索引转换为日期时间
如何将字符串索引转换为日期时间格式 我的数据帧'df'是这样的python可以将索引转换为日期时间,python,pandas,Python,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 但是索引是string类型的,但是我需要一个datetime
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
但是索引是string类型的,但是我需要一个datetime格式,因为我得到了错误
'Index' object has no attribute 'hour'
使用时
df['A'] = df.index.hour
它应该像预期的那样工作。尝试运行以下示例
import pandas as pd
import io
data = """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"""
df = pd.read_table(io.StringIO(data), delim_whitespace=True)
# Converting the index as date
df.index = pd.to_datetime(df.index)
# Extracting hour & minute
df['A'] = df.index.hour
df['B'] = df.index.minute
df
# value A B
# 2015-09-25 00:46:00 71.925000 0 46
# 2015-09-25 00:47:00 71.625000 0 47
# 2015-09-25 00:48:00 71.333333 0 48
# 2015-09-25 00:49:00 64.571429 0 49
# 2015-09-25 00:50:00 72.285714 0 50
我只是为这个问题提供了其他选项-您需要在代码中使用“.dt”:
将熊猫作为pd导入
df.index=pd.to_datetime(df.index)
#来年
df.index.dt.year
#月薪
df.index.dt.month
#为了得到一天
df.index.dt.day
#一小时
df.index.dt.hour
#一分钟
df.index.dt.minute
您可以在初始化数据帧时显式创建DatetimeIndex
。假设您的数据是字符串格式
data = [
('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, values = zip(*data)
frame = pd.DataFrame({
'values': values
}, index=pd.DatetimeIndex(index))
print(frame.index.minute)
在我的例子中,我的数据帧具有以下特征
<class 'pandas.core.frame.DataFrame'>
Index: 3040 entries, 15/12/2008 to
Data columns (total 1 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Close 3038 non-null float64
dtypes: float64(1)
memory usage: 47.5+ KB
索引:3040条,15/12/2008至
数据列(共1列):
#列非空计数数据类型
--- ------ -------------- -----
0关闭3038非空浮点64
数据类型:float64(1)
内存使用率:47.5+KB
第一个选项data.index=pd.to\u datetime(data.index)
返回
ParserError:String不包含日期:ParserError:String不包含日期:
第二个选项:data.index.to\u datetime()
返回
AttributeError:“Index”对象没有属性“to\u datetime”
它回来了
我测试过的另一个选项是data.index=pd.to\u datetime(data.index)
它返回:ParserError:String不包含日期:
我有什么问题?谢谢你这么做
df.index = pd.to_datetime(df.index, errors='coerce')
索引的数据类型已更改为
df.index.to_datetime()
或df.index=pandas.to_datetime(df.index)
(前者现在已被弃用)。type(df.index[1])仍然返回'str上述数据转换为datetime
没有问题-type(df.index[1])==pandabs.tslib Timestamp
。数据帧的其余部分是否有错误数据?您还可以指定格式和错误标记。的文档将解释Python3的rest.FYI,您需要index,values=zip(*data.items())