【问题标题】:PyMongo query gives me back a nested DataFramePyMongo 查询给了我一个嵌套的 DataFrame
【发布时间】:2020-05-25 14:53:53
【问题描述】:

我对一个非常大的数据集执行聚合。这是我的代码:

pipeline = [{"$match": {"Name_md_group": "ZEITUNGEN"}}, {"$group": {"_id": {"Name_freq": "$Name_freq"}, "total": {"$sum": "$Cost"}}}]
result = pd.DataFrame(list(collection.aggregate(pipeline)))

结果:

                                          _id         total
    0  {'Name_freq': 'WOECHENTLICH FUENFMAL'}  2.074940e+07
    1               {'Name_freq': 'SONSTIGE'}  2.284889e+07
    2           {'Name_freq': 'WOECHENTLICH'}  8.522535e+07
    3               {'Name_freq': 'TAEGLICH'}  3.700943e+07
    4  {'Name_freq': 'WOECHENTLICH SECHSMAL'}  1.489394e+09

不知怎的,我得到了一个嵌套对象?为什么会这样,有没有办法摆脱它?列名_id 应为Name_freq。谁能帮帮我?

【问题讨论】:

    标签: python python-3.x mongodb aggregation-framework pymongo


    【解决方案1】:

    将表达式直接放入_id 并添加一个额外的$project 阶段。

    pipeline = [
      { $match: { Name_md_group: "ZEITUNGEN" } },
      { $group: { _id: "$Name_freq", total: { $sum: "$Cost" } } },
      { $project: { Name_freq: "$_id", _id: 0, total: 1 }}
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多