Python Pandas CSV 到嵌套字典,用于在 mongodb 中上传数据

Python Pandas CSV to nested dictionary for uploading data in mongodb

我有一个这样的 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 片段。但是,我尝试使用 groupby 方法,但没有获得所需的输出。

{
    '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},
    },
]