python - 使用 Python 将 Pandas 数据框中的行作为单个文档插入到 mongodb 集合中

标签 python mongodb pandas dataframe pymongo

我一直在尝试将 pandas 数据框的行作为单独的文档插入到 mongodb 集合中。我正在使用 pymongo 从 MongoDB 中提取数据,执行一些转换,运行评分算法,并将分数作为附加列添加到数据框。最后一步是将行作为单独的文档插入到 mongoDB 数据库的一个特殊集合中,但我完全被卡住了。我的示例数据框 df 如下所示。

    memberID                                       dxCodes  dxCount  score
0  856589080          [4280, 4293, 4241, 4240, 4242, 4243]        6    1.8 
1  906903383                                       [V7612]        1    2.6
2  837210554                           [4550, 4553, V1582]        3    3.1
3  935634391       [78791, 28860, V1582, 496, 25000, 4019]        6    1.1
4  929185103  [30500, 42731, 4280, 496, 59972, 4019, 3051]        7    2.8

MemberID 是一个字符串,dx codes 是一个数组(在 MongoDB 术语中),dxCount 是一个 int,而 score 是一个 float。我一直在研究我发现的一段代码,以回应一个模糊的类似问题。

import json
import datetime
df = pandas.DataFrame.from_dict({'A': {1: datetime.datetime.now()}})
records = json.loads(df.T.to_json()).values()     
db.temp.insert_many(records) 

这是我能够在我的收藏中得到的:

{
    "_id" : ObjectId("565a8f206d8bc51a08745de0"),
    "A" : NumberLong(1448753856695)
}

它不多,但它是我所得到的最接近的。我花了很多时间在黑暗中用谷歌搜索和拍照,但还没有破解它。非常感谢任何指导,提前感谢您的帮助!

最佳答案

您需要使用 .to_dict() 将 DataFrame 转换为字典列表方法。

>>> from pprint import pprint # to pretty print the cursor result.
>>> import pandas as pd
>>> import pymongo
>>> client = pymongo.MongoClient()
>>> db = client.test
>>> collection = db.collection
>>> memberID = ['856589080', '906903383', '837210554', '935634391', '929185103']
>>> dxCodes = [[4280, 4293, 4241, 4240, 4242, 4243], [7612], [4550, 4553, 1582],[78791, 28860, 1582, 496, 25000, 4019], [30500, 42731, 4280, 496, 59972, 4019, 3051]]
>>> dxCount = [6, 1, 3, 6, 7]
>>> score = [1.8, 2.6, 3.1, 1.1, 2.8]
>>> df = pd.DataFrame({'memberID': memberID, 'dxCodes': dxCodes, 'score': score})
>>> df
                                        dxCodes   memberID  score
0          [4280, 4293, 4241, 4240, 4242, 4243]  856589080    1.8
1                                        [7612]  906903383    2.6
2                            [4550, 4553, 1582]  837210554    3.1
3        [78791, 28860, 1582, 496, 25000, 4019]  935634391    1.1
4  [30500, 42731, 4280, 496, 59972, 4019, 3051]  929185103    2.8
>>> collection.insert_many(df.to_dict('records')) # you need to pass the 'records' as argument in order to get a list of dict.
<pymongo.results.InsertManyResult object at 0x7fcd7035d990>
>>> pprint(list(collection.find()))
[{'_id': ObjectId('565b189f0acf45181c69d464'),
  'dxCodes': [4280, 4293, 4241, 4240, 4242, 4243],
  'memberID': '856589080',
  'score': 1.8},
 {'_id': ObjectId('565b189f0acf45181c69d465'),
  'dxCodes': [7612],
  'memberID': '906903383',
  'score': 2.6},
 {'_id': ObjectId('565b189f0acf45181c69d466'),
  'dxCodes': [4550, 4553, 1582],
  'memberID': '837210554',
  'score': 3.1},
 {'_id': ObjectId('565b189f0acf45181c69d467'),
  'dxCodes': [78791, 28860, 1582, 496, 25000, 4019],
  'memberID': '935634391',
  'score': 1.1},
 {'_id': ObjectId('565b189f0acf45181c69d468'),
  'dxCodes': [30500, 42731, 4280, 496, 59972, 4019, 3051],
  'memberID': '929185103',
  'score': 2.8}]
>>> 

关于python - 使用 Python 将 Pandas 数据框中的行作为单个文档插入到 mongodb 集合中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33979983/

相关文章:

python - 使用 Python 图像库模糊包含文本的图像

python - 从输入文件创建数据框

java - 如何解决这个 Morphia 映射问题??? ---> 警告 [org.mongodb.morphia.mapping.DefaultCreator] - 未在 dbObj : 中找到定义的类

mysql - 使用 Pandas 插入 MySQL 替换内容

python - Scikit-learn(SVC 估计器)总是给出相同的预测值

python - Latex 中的\def 错误

arrays - 为什么我的 For 循环在 EJS Node js 中只返回一个值?

python - 如何在Flask中访问MongoDB实例

python - “.. in pandas..html.py .. self.fmt.col_space.items()” : AttributeError: 'NoneType' object has no attribute 'items'

python - 在 Pandas 中,根据不同模式选择多列的惯用方式是什么?