gpt4 book ai didi

python - 将 PeriodIndex 转换为 DateTimeIndex?

转载 作者:太空狗 更新时间:2023-10-30 00:44:27 24 4
gpt4 key购买 nike

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

我有一个如下所示的 DataFrame:

               colors      countrytime_month 2010-09         xxx        xxx2010-10         xxx        xxx2010-11         xxx        xxx...

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),

VAR(mdata)

返回:

Given a pandas object and the index does not contain dates

很明显,Period 不被识别为日期时间。现在,我的问题是如何将索引 (time_month) 转换为 VAR 分析可以使用的日期时间?

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

返回

cannot convert Int64Index->DatetimeIndex

感谢您的帮助!

最佳答案

为此,您可以使用 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

在旧版本的 Pandas 中,方法是 to_datetime

关于python - 将 PeriodIndex 转换为 DateTimeIndex?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29394730/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com