将PeriodIndex转换为DateTimeIndex

将PeriodIndex转换为DateTimeIndex

本文介绍了将PeriodIndex转换为DateTimeIndex?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于将tseries.period.PeriodIndex转换为日期时间的问题.

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

我有一个看起来像这样的DataFrame:

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是索引.

time_month is the index.

type(df.index)

返回

class 'pandas.tseries.period.PeriodIndex'

当我尝试使用df进行VAR分析时( http://statsmodels.sourceforge.net/devel/vector_ar.html#vector-autoregressions-tsa-vector-ar ),

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)

返回:

Given a pandas object and the index does not contain dates

因此,显然,Period无法识别为日期时间.现在,我的问题是如何将索引(time_month)转换为VAR分析可以使用的日期时间?

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)

返回

cannot convert Int64Index->DatetimeIndex

感谢您的帮助!

推荐答案

您可以对此使用PeriodIndex的to_timestamp方法:

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

在较早版本的Pandas中,方法为to_datetime

In older versions of Pandas the method was to_datetime

这篇关于将PeriodIndex转换为DateTimeIndex?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:33