【发布时间】:2020-02-16 13:56:43
【问题描述】:
我有一个带有嵌入列表的文档结构,在我使用聚合管道展开后,我得到以下结果。
注意:我使用 Python 和 pymongo 进行此查询。
pipeline = [
{'$unwind': '$saved_alloys'},
{
'$project': {
'_id': 0,
'name': '$saved_alloys.name',
'compositions': '$saved_alloys.compositions'
}
}
]
res = db['alloys'].aggregate(pipeline)
for e in res:
print(e)
输出(截断):
{
'name': 'alloy-1',
'compositions': [
{'symbol': 'C', 'weight': 0.36},
{'symbol': 'Mn', 'weight': 1.41}
{'symbol': 'Si', 'weight': 1.03},
{'symbol': 'Ni', 'weight': 1.7}
]
}
{
'name': 'alloy-2',
'compositions': [
{'symbol': 'C', 'weight': 0.21},
{'symbol': 'Mn', 'weight': 0.23},
{'symbol': 'Si', 'weight': 0.86},
{'symbol': 'Ni', 'weight': 0.67},
{'symbol': 'Cr', 'weight': 0.12},
]
}
...
我正在尝试通过将组合的维度减少到笛卡尔平面来对此进行一些数据分析。因此,我想通过 pd.DataFrame(list(res)) 将其放入 pandas DataFrame。
我想最终得到一个具有以下结构的表:
{
"name": "alloy-1",
"C": 0.36,
"Mn": 1.41,
"Si": 1.03,
"Ni": 1.7,
"Cr": 0.0
},
{
"name": "alloy-2",
"C": 0.21,
"Mn": 0.23,
"Si": 0.86,
"Ni": 0.67,
"Cr": 0.12
}
请注意,compositions 列表的大小可能是可变的,因此对于那些不在列表中的元素,我想添加它们,但 weights 的值为零(如 alloy-1 中的 @987654328 @)。
提前感谢您的帮助。
【问题讨论】:
标签: python mongodb aggregation