使用 PyMongo 将 Pandas Dataframe 插入 mongodb [英] Insert a Pandas Dataframe into mongodb using PyMongo
问题描述
使用 PyMongo
将 Pandas DataFrame 插入 mongodb 的最快方法是什么?
尝试
db.myCollection.insert(df.to_dict())
出现错误
<块引用>InvalidDocument:文档必须只有字符串键,键是时间戳('2013-11-23 13:31:00', tz=None)
<小时>
db.myCollection.insert(df.to_json())
出现错误
<块引用>TypeError: 'str' 对象不支持项目分配
<小时>
db.myCollection.insert({id: df.to_json()})
出现错误
InvalidDocument: 文档必须只有字符串a键,键是<内置函数id>
df
日期时间索引:150 个条目,2013-11-23 13:31:26 到 2013-11-23 13:24:07数据列(共3列):数量 150 个非空值价格 150 个非空值tid 150 个非空值数据类型:float64(2)、int64(1)
我怀疑是否有最快和简单的方法.如果你不担心数据转换,你可以做
<预><代码>>>>导入json>>>df = pd.DataFrame.from_dict({'A': {1: datetime.datetime.now()}})>>>df一种1 2013-11-23 21:14:34.118531>>>记录 = json.loads(df.T.to_json()).values()>>>db.myCollection.insert(记录)但如果您尝试加载数据,你会得到:
<预><代码>>>>df = read_mongo(db, 'myCollection')>>>df一种0 1385241274118531000>>>df.dtypes一个 int64数据类型:对象因此您必须将A"列转换回 datetime
s,以及所有不是 int
、float
或 <DataFrame
中的 code>str 字段.对于这个例子:
What is the quickest way to insert a pandas DataFrame into mongodb using PyMongo
?
Attempts
db.myCollection.insert(df.to_dict())
gave an error
InvalidDocument: documents must have only string keys, the key was Timestamp('2013-11-23 13:31:00', tz=None)
db.myCollection.insert(df.to_json())
gave an error
TypeError: 'str' object does not support item assignment
db.myCollection.insert({id: df.to_json()})
gave an error
InvalidDocument: documents must have only string a keys, key was <built-in function id>
df
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 150 entries, 2013-11-23 13:31:26 to 2013-11-23 13:24:07
Data columns (total 3 columns):
amount 150 non-null values
price 150 non-null values
tid 150 non-null values
dtypes: float64(2), int64(1)
I doubt there is a both quickest and simple method. If you don't worry about data conversion, you can do
>>> import json
>>> df = pd.DataFrame.from_dict({'A': {1: datetime.datetime.now()}})
>>> df
A
1 2013-11-23 21:14:34.118531
>>> records = json.loads(df.T.to_json()).values()
>>> db.myCollection.insert(records)
But in case you try to load data back, you'll get:
>>> df = read_mongo(db, 'myCollection')
>>> df
A
0 1385241274118531000
>>> df.dtypes
A int64
dtype: object
so you'll have to convert 'A' columnt back to datetime
s, as well as all not int
, float
or str
fields in your DataFrame
. For this example:
>>> df['A'] = pd.to_datetime(df['A'])
>>> df
A
0 2013-11-23 21:14:34.118531
这篇关于使用 PyMongo 将 Pandas Dataframe 插入 mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!