【发布时间】: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