我有一个这样的DataFrame,我想要一个如下所示的结果:
Country, ESG, Pillar, Series, 2012, 2013, Last Updated
Nepal, Social, health, clean fuels, 24.6, 26.1, 05/01/2021
Nepal, Environment, Food, agriculture,30.0, 28.62, 05/01/2021
Nepal,Environment,Food, land, 28.0, 27.0, 05/01/2021
我想把这些数据上传到MongoDB,我想要的结构格式如下所示,作为一个python代码片段。我尝试了分组方法,但是,我没有达到预期的输出。
{
'Country': 'Nepal',
{
'ESG': 'Social',
'Pillar': 'health',
'clean fuels:
{
'2012': 24.6,
'2013': 26.1
}
},
'last Updated': 05/01/2021
}
有人能帮我解决这个问题吗?尝试:
out = [
{
**row[["Country", "Last Updated"]].to_dict(),
**{row["Series"]: row.filter(regex=r"d{4}").to_dict()},
}
for _, row in df.iterrows()
]
print(out)
打印:
[
{
"Country": "Nepal",
"Last Updated": "05/01/2021",
"clean fuels": {"2012": 24.6, "2013": 26.1},
},
{
"Country": "Nepal",
"Last Updated": "05/01/2021",
"agriculture": {"2012": 30.0, "2013": 28.62},
},
{
"Country": "Nepal",
"Last Updated": "05/01/2021",
"land": {"2012": 28.0, "2013": 27.0},
},
]