pandas 将 PeriodIndex 转换为 DateTimeIndex?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29394730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting PeriodIndex to DateTimeIndex?
提问by Christopher
I have a question regarding converting a tseries.period.PeriodIndex into a datetime.
我有一个关于将 tseries.period.PeriodIndex 转换为日期时间的问题。
I have a DataFrame which looks like this:
我有一个如下所示的 DataFrame:
colors country time_month 2010-09 xxx xxx 2010-10 xxx xxx 2010-11 xxx xxx ...
time_month is the index.
time_month 是索引。
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),
当我尝试使用 df 进行 VAR 分析时(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?
很明显,Period 不被识别为日期时间。现在,我的问题是如何将索引 (time_month) 转换为 VAR 分析可以使用的日期时间?
df.index = pandas.DatetimeIndex(df.index)
returns
回报
cannot convert Int64Index->DatetimeIndex
Thank for your help!
感谢您的帮助!
回答by joris
You can use the to_timestampmethod of PeriodIndex for this:
您可以to_timestamp为此使用PeriodIndex的方法:
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
在旧版本的 Pandas 中,方法是 to_datetime
回答by Sarah
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')

