在另一个问题中,有人试图使用Python内部结构(dict
,list
) Insert a Pandas Dataframe into mongodb using PyMongo将熊猫DataFrame插入到MongoDB中
我想知道我们是否不能使用PyMongo将NumPy rec.array
(numpy.recarray
)插入到MongoDB中。
这可能会更有效,因为pandas.DataFrame.to_dict
使用for循环,而且处理大量数据需要很长时间
In [1]: import pandas as pd
In [2]: import pymongo
In [3]: client = pymongo.MongoClient()
In [4]: collection = client['db_name']['collection_name']
In [5]: df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a', 'b', 'c'])
In [6]: df
Out[6]:
a b c
0 1 2 3
1 4 5 6
In [7]: rec = df.to_records()
In [8]: rec
Out[8]:
rec.array([(0, 1, 2, 3), (1, 4, 5, 6)],
dtype=[('index', '<i8'), ('a', '<i8'), ('b', '<i8'), ('c', '<i8')])
In [9]: type(rec)
Out[9]: numpy.recarray
但是我在插入时遇到了一些错误
In [10]: collection.insert(rec)
已引发
ValueError: no field of name _id
这
In [11]: collection.insert_many(rec)
已引发
TypeError: documents must be a non-empty list
这
In [12]: collection.insert_one(rec)
已引发
TypeError: document must be an instance of dict, bson.son.SON, or other type that inherits from collections.MutableMapping
有什么想法吗?
发布于 2015-12-27 17:22:57
Odo可以做到这一点
In [1]: import pandas as pd
In [2]: import pymongo
In [3]: client = pymongo.MongoClient()
In [4]: collection = client['db_name']['collection_name']
In [5]: df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a', 'b', 'c'])
In [6]: rec = df.to_records(index=False)
In [7]: from odo import odo
In [8]: odo(rec, collection) # migrate recarray into collection
Out[8]: Collection(Database(MongoClient('localhost', 27017), 'db_name'), 'collection_name')
In [9]: list(collection.find())
Out[9]:
[{'_id': ObjectId('56801e0bfb5d1b19ff9b9dd3'), 'a': 1, 'b': 2, 'c': 3},
{'_id': ObjectId('56801e0bfb5d1b19ff9b9dd4'), 'a': 4, 'b': 5, 'c': 6}]
然而,它只是通过字典的迭代器(因此在这方面与其他解决方案一样效率低下)。如果你真的想高效地发送二进制数据,那么你应该看看monary。
但是for循环不一定是这里的瓶颈。我强烈建议做一些简单的基准测试,以验证在这里转换到Python数据结构是您的应用程序的瓶颈。您可能过早地进行了优化。
https://stackoverflow.com/questions/34482707
复制相似问题