mongo的小组结果是熊猫的DataFrame

时间:2016-04-26 17:57:46

标签: python mongodb pandas dataframe

是否有任何方便的方法可以将mongodb组操作的结果加载到pandas DataFrame中?

以下是mongo查询的分组类型:

    '$group': {
        '_id': {'country': '$country', 'oem':'$oem'},
         'count': {'$sum': 1}
    }

这是一个字典列表,如下所示:

[
   ...
   { "_id" : { "country" : "US", "oem" : "mmm" }, "count" : 595 },
   ...
]

我希望将其加载到DataFrame中,以便countryoem自动成为索引。如果没有重新映射结果,Pandas API中是否有任何可以处理此问题的内容?或者我可以以某种方式重新编写mongo查询,以便它返回一个对pandas API更友好的结构?

1 个答案:

答案 0 :(得分:0)

您可以使用json_normalize()

In [59]: l
Out[59]:
[{'_id': {'country': 'UA', 'oem': 'uuuu'}, 'count': 555},
 {'_id': {'country': 'US', 'oem': 'aaaa'}, 'count': 595},
 {'_id': {'country': 'DE', 'oem': 'bbbb'}, 'count': 777}]

In [60]: from pandas.io.json import json_normalize

In [61]: l
Out[61]:
[{'_id': {'country': 'UA', 'oem': 'uuuu'}, 'count': 555},
 {'_id': {'country': 'US', 'oem': 'aaaa'}, 'count': 595},
 {'_id': {'country': 'DE', 'oem': 'bbbb'}, 'count': 777}]

In [62]: json_normalize(l)
Out[62]:
  _id.country _id.oem  count
0          UA    uuuu    555
1          US    aaaa    595
2          DE    bbbb    777

设置:

l = [
   { "_id" : { "country" : "UA", "oem" : "uuuu" }, "count" : 555 },
   { "_id" : { "country" : "US", "oem" : "aaaa" }, "count" : 595 },
   { "_id" : { "country" : "DE", "oem" : "bbbb" }, "count" : 777 },
]