python pandas将index转换为datetime

时间:2016-11-26 05:22:29

标签: python pandas

如何将字符串的pandas索引转换为datetime格式

我的数据框'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

5 个答案:

答案 0 :(得分:49)

它应该按预期工作。尝试运行以下示例。

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

答案 1 :(得分:1)

初始化数据框时,可以显式创建 }。假设您的数据是字符串格式

DatetimeIndex

答案 2 :(得分:0)

对于这个问题,我只是提供其他选择-您需要在代码中使用“ .dt”:

import pandas as pd

df.index = pd.to_datetime(df.index)

#for get year
df.index.dt.year

#for get month
df.index.dt.month

#for get day
df.index.dt.day

#for get hour
df.index.dt.hour

#for get minute
df.index.dt.minute

答案 3 :(得分:0)

就我而言,我的数据框具有以下特征

<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

enter image description here

返回第一个选项 data.index = pd.to_datetime(data.index)

解析器错误:字符串不包含日期:ParserError: String does not contain a date:

第二个选项:data.index.to_datetime() 返回

AttributeError: 'Index' object has no attribute 'to_datetime'

它回来了

我测试过的另一个选项是。 data.index = pd.to_datetime(data.index)

它返回:ParserError: String does not contain a date:

我的问题是什么?谢谢

答案 4 :(得分:0)

df.index = pd.to_datetime(df.index, errors='coerce')

索引的数据类型已更改为

dataframe information