Converting PeriodIndex to DateTimeIndex?

人盡茶涼 提交于 2019-12-19 03:14:10

问题


I have a question regarding converting a tseries.period.PeriodIndex into a datetime.

I have a DataFrame which looks like this:

               colors      country
time_month 

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

time_month is the index.

type(df.index)

returns

class 'pandas.tseries.period.PeriodIndex'

When I try to use the df for a VAR analysis (http://statsmodels.sourceforge.net/devel/vector_ar.html#vector-autoregressions-tsa-vector-ar),

VAR(mdata)

returns:

Given a pandas object and the index does not contain dates

So apparently, Period is not recognized as a datetime. Now, my question is how to convert the index (time_month) into a datetime the VAR analysis can work with?

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

returns

cannot convert Int64Index->DatetimeIndex

Thank for your help!


回答1:


You can use the to_timestamp method of PeriodIndex for this:

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

In older versions of Pandas the method was to_datetime




回答2:


You can also use the following to get exactly the same result.

idx.astype('datetime64[ns]') 

To convert back to period, you can do:

 idx.to_period(freq='D')


来源:https://stackoverflow.com/questions/29394730/converting-periodindex-to-datetimeindex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!