如何在pandas dataframe中将int索引转换为日期索引?

时间:2016-01-20 14:16:50

标签: python pandas

我使用pandas在python中创建了一个数据帧。使用的索引是一系列int64类型的时间戳。但是,对于时间序列分析,索引需要是类型日期。有人可以帮我做转换吗?

>>> import pandas as pd
>>> import time
>>> import statsmodels.api as sm
>>> df = pd.DataFrame(columns=['TCA', 'TCB', 'TCC'])
>>> df.loc[int(time.time() * 1000)] = [1, 2, 3]
>>> df.index
Int64Index([1453299087814], dtype='int64')
>>> arma_mod21 = sm.tsa.ARMA(df['TCA'], (2, 1)).fit()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/statsmodels-0.6.1-py2.7-macosx-10.6-intel.egg/statsmodels/tsa/arima_model.py", line 445, in __init__
    super(ARMA, self).__init__(endog, exog, dates, freq, missing=missing)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/statsmodels-0.6.1-py2.7-macosx-10.6-intel.egg/statsmodels/tsa/base/tsa_model.py", line 42, in __init__
    self._init_dates(dates, freq)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/statsmodels-0.6.1-py2.7-macosx-10.6-intel.egg/statsmodels/tsa/base/tsa_model.py", line 51, in _init_dates
    raise ValueError("Given a pandas object and the index does "
ValueError: Given a pandas object and the index does not contain dates

1 个答案:

答案 0 :(得分:4)

使用to_datetimeunit='ms'转换为datetime

In [185]:
pd.to_datetime(df.index, unit='ms')

Out[185]:
DatetimeIndex(['2016-01-20 14:16:51.703000'], dtype='datetime64[ns]', freq=None)

In [187]:
df.index = pd.to_datetime(df.index, unit='ms')
df.index

Out[187]:
DatetimeIndex(['2016-01-20 14:16:51.703000'], dtype='datetime64[ns]', freq=None)