我试着用熊猫库来分析蟒蛇的时间序列。我的数据现在存储在字典列表中:
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当我要求索引为DataFrame时,如何从列表中创建DateTimeIndex
发布于 2014-07-17 02:16:54
还可以直接将索引转换为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发布于 2014-07-17 02:12:25
熊猫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')不过,请确保运行的是最近的版本。在抛出与DateTimeIndex相关的错误时,0.11及以下版本甚至更特殊(也更不有用)。
发布于 2014-07-17 02:11:57
您可以使用pandas.to_datetime()函数自动将类型转换为datetime。查看本教程:http://pandas.pydata.org/pandas-docs/dev/timeseries.html它有许多用于时间序列分析的基本用法。
https://stackoverflow.com/questions/24793679
复制相似问题