【问题标题】:Construct pandas DataFrame from items in 3 level nested dictionary with to list of values从具有值列表的 3 级嵌套字典中的项目构造 pandas DataFrame
【发布时间】:2023-01-21 09:27:31
【问题描述】:

我有以下字典:

dict = {
"Building 1": {
    "Energy consumption": {
        "Datetime": ["2020-12-28","2021-01-04"],
        "Value": [537,967]},
     "Water consumption": {
        "Datetime": ["2020-12-28","2021-01-04"],
        "Value": [537,967]}},
"Building 2": {
    "Energy consumption": {
        "Datetime": ["2020-12-28","2021-01-04"],
        "Value": [600,700]},
     "Water consumption": {
        "Datetime": ["2020-12-28","2021-01-04"],
        "Value": [800,500]}}
       }

我想将字典转换为熊猫数据框。我认为最好的方法是得到类似的东西:

enter image description here

尝试了几种方法都没有成功,有人知道如何解决这个问题吗?

【问题讨论】:

    标签: python pandas dictionary


    【解决方案1】:

    只需使用列表来存储建筑物编号并使用索引来引用建筑物。您还可以将索引列的名称更改为Building。换句话说,你不需要Building 1Building 2、...、Building n

    import pandas as pd
    
    data = [
    
        {
            "Energy consumption": {
                "Datetime": ["2020-12-28","2021-01-04"],
                "Value": [537,967]},
            "Water consumption": {
                "Datetime": ["2020-12-28","2021-01-04"],
                "Value": [537,967]}
        },
    
        {
            "Energy consumption": {
                "Datetime": ["2020-12-28","2021-01-04"],
                "Value": [600,700]},
            "Water consumption": {
                "Datetime": ["2020-12-28","2021-01-04"],
                "Value": [800,500]}
        }
    ]
    
    df = pd.DataFrame.from_dict(data)
    
    print(df)
    

    输出:

                                      Energy consumption                                  Water consumption
    0  {'Datetime': ['2020-12-28', '2021-01-04'], 'Va...  {'Datetime': ['2020-12-28', '2021-01-04'], 'Va...
    1  {'Datetime': ['2020-12-28', '2021-01-04'], 'Va...  {'Datetime': ['2020-12-28', '2021-01-04'], 'Va...
    

    【讨论】:

    • 不幸的是,您的输出没有提供以日期作为行索引和值的多索引列。我希望其他人确实知道该怎么做!谢谢
    【解决方案2】:

    嵌套字典的结构有点复杂。您可以先使用 unstack 获取多索引列,然后转换单元格值以创建新的数据框:

    series = pd.DataFrame(data).unstack()
    cols = series.index
    s = series.apply(lambda x: dict(zip(x["Datetime"], x["Value"])))
    pd.DataFrame(s.values.tolist(), index=cols).T
    

    输出:

                       Building 1                           Building 2                  
               Energy consumption Water consumption Energy consumption Water consumption
    2020-12-28                537               537                600               800
    2021-01-04                967               967                700               500
    

    【讨论】:

      猜你喜欢
      • 2012-11-14
      • 2021-12-31
      • 2015-08-03
      • 2016-07-24
      • 2023-04-02
      • 2018-05-05
      • 2015-10-25
      • 2017-12-26
      • 1970-01-01
      相关资源
      最近更新 更多