gpt4 book ai didi

python - mongo的分组结果到pandas DataFrame

转载 作者:太空宇宙 更新时间:2023-11-03 16:40:14 24 4
gpt4 key购买 nike

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

最佳答案

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

关于python - mongo的分组结果到pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36872386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com