2016-01-20 63 views
2

我已经使用熊猫在python中创建了一个数据框。使用的索引是一系列类型为int64的时间戳。但是,对于时间序列分析,索引需要是类型日期。有人可以帮我做转换吗?如何将int index转换为熊猫数据框中的日期索引?


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

[转换时间戳datetime.datetime在pandas.Series](可能的复制http://stackoverflow.com/questions/22554339 /转换时间戳到日期时间,日期时间,在-熊猫系列) – sobek

回答

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) 
相关问题