使用 MongoDB 列表中的日期字段作为 Pandas DataFrame 中的 DatetimeIndex

Use date field from MongoDB list as DatetimeIndex in Pandas DataFrame

我正在从 MongoDB 集合中读取数据

mongo_url = 'mongodb://localhost:27017/db'
client = pymongo.MongoClient(mongo_url)
db = client.db
collection = db.coll
docs = list(collection.find({}, {"Date": 1, "Cost" : 1, "_id" : 0 }).sort("date", pymongo.ASCENDING))

所以我最终得到了存储在文档中的字典列表,形式为

[{u'Date': u'2008-01-01', u'Cost': 8557.0}, {u'Date': u'2008-01-02', u'Cost': 62307.0},.....]

然后我可以从这个

创建一个 DataFrame
frame = DataFrame(docs)

其形式为

但我希望 日期 列用作 DatetimeIndex。我一直在以一种非常老套的方式来做这件事,但我知道必须有一种更简洁的方式来做这件事。

frame = frame.set_index(pd.to_datetime(frame['Date']))

此外,如果我检查索引,我发现 freq 不存在,所以我想在创建 DataFrame

时尝试设置每日频率


更新

@jezrael 的回答非常好,所以我只想在这里解释一下哪种方法对我有用。

如果我试试这个

frame = DataFrame(docs)
frame.set_index('Date', inplace=True)
frame.index = pd.DatetimeIndex(frame.index, freq='D')

出于某种原因,我收到以下错误

ValueError: Inferred frequency None from passed dates does notconform to passed frequency D

但是另一个建议对我来说很管用。

idx =  pd.DatetimeIndex([x['Date'] for x in docs], freq='D')
frame = DataFrame(docs, index=idx)
frame = frame.drop('Date', 1)

如果需要在DataFrame构造函数中创建Datetimindex

docs = [{u'Date': u'2008-01-01', u'Cost': 8557.0},{u'Date': u'2008-01-02', u'Cost': 62307.0}]

idx =  pd.DatetimeIndex([x['Date'] for x in docs], freq='D')
print (idx)
DatetimeIndex(['2008-01-01', '2008-01-02'], dtype='datetime64[ns]', freq='D')

frame = pd.DataFrame(docs, index=idx)
print (frame)
               Cost        Date
2008-01-01   8557.0  2008-01-01
2008-01-02  62307.0  2008-01-02

print (frame.index)
DatetimeIndex(['2008-01-01', '2008-01-02'], dtype='datetime64[ns]', freq='D')

另一种解决方法,如果在创建DataFrame之后再创建DatetimeIndex

您可以使用 set_index with DatetimeIndex:

docs = [{u'Date': u'2008-01-01', u'Cost': 8557.0},{u'Date': u'2008-01-02', u'Cost': 62307.0}]
frame = pd.DataFrame(docs)
print (frame)
      Cost        Date
0   8557.0  2008-01-01
1  62307.0  2008-01-02

frame.set_index('Date', inplace=True)
frame.index = pd.DatetimeIndex(frame.index, freq='D')
print (frame)
               Cost
2008-01-01   8557.0
2008-01-02  62307.0

print (frame.index)
DatetimeIndex(['2008-01-01', '2008-01-02'], dtype='datetime64[ns]', freq='D')

如果需要复制列Dateindex:

docs = [{u'Date': u'2008-01-01', u'Cost': 8557.0},{u'Date': u'2008-01-02', u'Cost': 62307.0}]
frame = pd.DataFrame(docs)
print (frame)
      Cost        Date
0   8557.0  2008-01-01
1  62307.0  2008-01-02

frame.set_index(frame.Date, inplace=True)
frame.index = pd.DatetimeIndex(frame.index, freq='D')
print (frame)
               Cost        Date
2008-01-01   8557.0  2008-01-01
2008-01-02  62307.0  2008-01-02
print (frame.index)
DatetimeIndex(['2008-01-01', '2008-01-02'], dtype='datetime64[ns]', freq='D')