Python 字典列表中的时间序列索引

Python 字典列表中的时间序列索引,python,dictionary,pandas,time-series,Python,Dictionary,Pandas,Time Series,我正在尝试使用pandas库在python中进行时间序列分析。 我的数据现在存储为字典列表: mydata = [ { 'date': datetime.date(2013, 1, 1), 'snow_depth': 1.0, }, { 'date': datetime.date(2013, 1, 2), 'snow_depth': 2.5, }, { 'date': datetime.date(2013, 1, 3), 'snow_depth':

我正在尝试使用pandas库在python中进行时间序列分析。 我的数据现在存储为字典列表:

mydata = [
{
    'date': datetime.date(2013, 1, 1),
    'snow_depth': 1.0,
}, {
    'date': datetime.date(2013, 1, 2),
    'snow_depth': 2.5,
}, {
    'date': datetime.date(2013, 1, 3),
    'snow_depth': 8.0,
},
]
我使用以下命令获取数据帧:

df = pd.DataFrame(mydata).set_index('date')
但该索引不能识别为DateTimeIndex,只能识别为对象:

df.index
返回:
索引([2013-01-012013-01-022013-01-03],dtype='object')

所以,我不能在熊猫身上做一些时间序列操作,比如按月累计等等。当我运行
df.index
时,我希望得到如下结果:

<class 'pandas.tseries.index.DatetimeIndex'>
[2013-01-01, ..., 2013-01-03]
Length: 3, Freq: D, Timezone: None

[2013-01-01, ..., 2013-01-03]
长度:3,频率:D,时区:无

当我要求索引为
DateTimeIndex
时,如何从列表中创建数据帧?

您可以使用pandas.to\u datetime()函数将类型自动转换为datetime。查看本教程:
它有许多时间序列分析的基本用途

Pandas
DateTimeIndex
可能有点特殊。例如,它不喜欢
datetime.date
值。但是如果您将它们更改为
datetime.datetime
值,它将按预期工作。甚至是同一个电话签名

import datetime
import pandas as pd
mydata = [
{
    'date': datetime.datetime(2013, 1, 1),
    'snow_depth': 1.0,
}, {
    'date': datetime.datetime(2013, 1, 2),
    'snow_depth': 2.5,
}, {
    'date': datetime.datetime(2013, 1, 3),
    'snow_depth': 8.0,
},
]

df = pd.DataFrame(mydata).set_index('date')

不过,请确保您运行的是最新版本。0.11及以下版本对于抛出与
DateTimeIndex
相关的错误更为特殊(但帮助不大)。

您也可以直接将索引转换为
DateTimeIndex

In [159]: df.index = pd.DatetimeIndex(df.index)

In [160]: df.index
Out[160]: 
<class 'pandas.tseries.index.DatetimeIndex'>
[2013-01-01, ..., 2013-01-03]
Length: 3, Freq: None, Timezone: None
[159]中的
df.index=pd.DatetimeIndex(df.index)
In[160]:df.index
Out[160]:
[2013-01-01, ..., 2013-01-03]
长度:3,频率:无,时区:无

try,df.index=pd.to\u datetime(df.index)