从字典列表创建Pandas时间序列索引

3 投票
3 回答
2573 浏览
提问于 2025-04-18 13:38

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

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,
},
]

我用以下命令来获取一个DataFrame:

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

但是,索引并没有被识别为日期时间索引,而只是被当作一个普通对象:

df.index

返回结果是:Index([2013-01-01, 2013-01-02, 2013-01-03], dtype='object')

所以,我无法在Pandas中进行一些时间序列操作,比如按月汇总等等。当我运行df.index时,我希望得到类似这样的结果:

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

我该如何从这个列表创建DataFrame,并确保索引是DateTimeIndex呢?

3 个回答

2

你可以使用 pandas.to_datetime() 这个函数来自动把数据转换成日期时间格式。想了解更多,可以看看这个教程:http://pandas.pydata.org/pandas-docs/dev/timeseries.html,里面有很多关于时间序列分析的基础用法。

4

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相关的错误处理得更加严格(而且不太友好)。

2

你也可以直接把索引转换成一个 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

撰写回答