Chr*_*her 5 python datetime-format dataframe pandas
我有一个关于将tseries.period.PeriodIndex转换为日期时间的问题.
我有一个DataFrame,如下所示:
colors country time_month 2010-09 xxx xxx 2010-10 xxx xxx 2010-11 xxx xxx ...
time_month是索引.
type(df.index)
Run Code Online (Sandbox Code Playgroud)
回报
class 'pandas.tseries.period.PeriodIndex'
Run Code Online (Sandbox Code Playgroud)
当我尝试使用df进行VAR分析时(http://statsmodels.sourceforge.net/devel/vector_ar.html#vector-autoregressions-tsa-vector-ar),
VAR(mdata)
Run Code Online (Sandbox Code Playgroud)
收益:
Given a pandas object and the index does not contain dates
Run Code Online (Sandbox Code Playgroud)
显然,Period不被认为是日期时间.现在,我的问题是如何将索引(time_month)转换为VAR分析可以使用的日期时间?
df.index = pandas.DatetimeIndex(df.index)
Run Code Online (Sandbox Code Playgroud)
回报
cannot convert Int64Index->DatetimeIndex
Run Code Online (Sandbox Code Playgroud)
谢谢您帮忙!
jor*_*ris 10
您可以使用to_timestampPeriodIndex 的方法:
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
Run Code Online (Sandbox Code Playgroud)
在旧版本的Pandas中,方法是 to_datetime
您还可以使用以下方法获得完全相同的结果。
idx.astype('datetime64[ns]')
Run Code Online (Sandbox Code Playgroud)
要转换回期间,您可以执行以下操作:
idx.to_period(freq='D')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9386 次 |
| 最近记录: |