【问题标题】:Pandas time series index from list of dictionaries字典列表中的 Pandas 时间序列索引
【发布时间】:2014-07-17 01:56:23
【问题描述】:

我正在尝试使用 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,
},
]

我使用下面的命令来获取一个DataFrame:

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

但是索引不被识别为DateTimeIndex,而只是作为一个对象:

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

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

【问题讨论】:

  • 试试,df.index = pd.to_datetime(df.index)

标签: python dictionary pandas time-series


【解决方案1】:

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
    

    【讨论】:

      【解决方案3】:

      您可以使用 pandas.to_datetime() 函数将类型自动转换为日期时间。查看本教程:http://pandas.pydata.org/pandas-docs/dev/timeseries.html 它有许多时间序列分析的基本用法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-07
        • 2023-03-09
        • 2018-05-15
        • 2020-10-09
        • 2012-07-27
        • 1970-01-01
        • 2015-07-03
        • 2021-05-03
        相关资源
        最近更新 更多