将 Pandas 时间戳插入 Mongodb [英] Insert Pandas Timestamp into Mongodb

查看:53
本文介绍了将 Pandas 时间戳插入 Mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 PyMongo 将 Pandas DataFrame 插入 Mongodb.

I'm trying to insert a Pandas DataFrame into Mongodb using PyMongo.

df.head()

因为索引如果 Pandas DataFrame 是 DatetimeIndex,将 DataFrame 转换为 dict 并插入到 Mongodb:

Because the index if the Pandas DataFrame is a DatetimeIndex, converting the DataFrame to a dict and inserting it to Mongodb:

db.testCollection.insert( df.T.to_dict() )

导致错误:

InvalidDocument: documents must have only string keys, key was Timestamp('2016-04-07 09:30:00')

我们如何将DatetimeIndex转换成其他可以插入到Mongodb中的东西,然后在从Mongodb读取时仍然能够转换回DatetimeIndex?

How can we convert the DatetimeIndex to something else that can be inserted into Mongodb, and later still be able to be converted back to a DatetimeIndex when reading from Mongodb?

推荐答案

一个解决方案是在尝试存储在 MongoDB 之前将索引转换为 str,如下所示:

A solution would be that you turn index to str before attempting to store away in MongoDB, like this:

>> df.index = df.index.astype(str)
>> db.testCollection.insert(df.T.to_dict())

稍后再次从数据库中读取数据时,您可以将索引转换为时间戳:

When reading the data out of db again later you can turn index to timestamp:

>> df.index = pd.to_datetime(df.index)

希望能帮到你

这篇关于将 Pandas 时间戳插入 Mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆