gpt4 book ai didi

python - 如何将 int 索引转换为 pandas 数据框中的日期索引?

转载 作者:行者123 更新时间:2023-11-28 22:39:19 24 4
gpt4 key购买 nike

我使用 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

最佳答案

使用to_datetime使用 unit='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)

关于python - 如何将 int 索引转换为 pandas 数据框中的日期索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34902464/

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