2016-11-26 53 views
9

我如何串的大熊貓索引轉換爲datetime格式蟒蛇大熊貓轉換指數爲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 

但該指數是字符串類型,但我需要datetime格式,因爲我得到的錯誤

'Index' object has no attribute 'hour' 

使用

df['A'] = df.index.hour 
+0

'df.index.to_datetime()'或'df.index = pandas.to_datetime(df.index)'(前者現在已經過時)。 – AChampion

+0

類型(df.index [1])仍然返回'str' –

+0

上面的數據轉換爲'datetime'沒有問題 - type(df.index [1])== pandas.tslib.Timestamp'。數據框的其餘部分是否有錯誤的數據? – AChampion

回答

18

它應該按預期工作。嘗試運行以下示例。

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