2015-04-01 41 views
2

我有一個關於將tseries.period.PeriodIndex轉換爲日期時間的問題。將PeriodIndex轉換爲DateTimeIndex?

我有一個數據幀,看起來像這樣:

    colors  country 
time_month 

2010-09   xxx  xxx 
2010-10   xxx  xxx 
2010-11   xxx  xxx 
... 

time_month是索引。

type(df.index) 

回報

class 'pandas.tseries.period.PeriodIndex' 

當我嘗試使用df的VAR分析(http://statsmodels.sourceforge.net/devel/vector_ar.html#vector-autoregressions-tsa-vector-ar),

VAR(mdata) 

回報:

Given a pandas object and the index does not contain dates 

因此很明顯,週期不被認爲是一個 約會時間。現在,我的問題是如何將索引(time_month)轉換爲VAR分析可以使用的日期時間?

df.index = pandas.DatetimeIndex(df.index) 

回報

cannot convert Int64Index->DatetimeIndex 

感謝您的幫助!

回答

6

可以使用PeriodIndex的to_timestamp方法是:

In [25]: pidx = pd.period_range('2012-01-01', periods=10) 

In [26]: pidx 
Out[26]: 
<class 'pandas.tseries.period.PeriodIndex'> 
[2012-01-01, ..., 2012-01-10] 
Length: 10, Freq: D 

In [27]: pidx.to_timestamp() 
Out[27]: 
<class 'pandas.tseries.index.DatetimeIndex'> 
[2012-01-01, ..., 2012-01-10] 
Length: 10, Freq: D, Timezone: None 

在較早版本的熊貓的方法是to_datetime

+0

這解決了它!出於某種原因,我以前必須犯過語法錯誤。 – Christopher 2015-04-01 15:30:46

+1

@Christopher BTW,一般來說,如果答案能夠解決問題,您應該嘗試將問題標記爲已解決(這也適用於您的其他問題) – joris 2015-04-01 17:35:05

相關問題