使用Python

时间:2015-11-29 06:14:48

标签: 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代码是一个数组(在MongoDB术语中),dxCount是一个int,得分是一个浮点数。我一直在用我发现的一段代码来回应一个模糊的类似问题。

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)
}

它并不多,但它和我一样接近。我花了很多时间在谷歌上搜索并在黑暗中拍摄但尚未破解它。非常感谢任何指导,感谢您的帮助!

1 个答案:

答案 0 :(得分:5)

您需要使用.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}]
>>>