【问题标题】:mongo's group results to panda's DataFramemongo 的组结果到 pandas DataFrame
【发布时间】:2016-08-20 17:19:36
【问题描述】:

是否有任何方便的方法可以将 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 更友好的结构?

【问题讨论】:

  • 你的预期输出是什么?
  • 具有三列的数据框:countryoemcount(可选地由 countryoem 索引)

标签: python mongodb pandas dataframe


【解决方案1】:

你可以使用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 },
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-11
    • 2022-11-03
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    • 2017-12-30
    相关资源
    最近更新 更多