【问题标题】:Convert pandas DataFrame to arbitrary nested JSON data将 pandas DataFrame 转换为任意嵌套的 JSON 数据
【发布时间】:2020-03-01 20:27:32
【问题描述】:

假设我有一个名为 df 的 pandas DataFrame,它看起来像:

source      tables      columns      
src1        table1      col1       
src1        table1      col2
src1        table2      col1 
src2        table1      col1
src2        table1      col2

我下面的当前代码可以遍历源列表并将每个源中的表列表嵌套为一个对象:

data = [
    {k: v} 

    for k, v in df.groupby('source')['tables'].agg(
        lambda x: {v: {} for v in x}).items()
    ]

    with open('data.json', 'w') as f:
        json.dump(data, f, indent = 2)

我收到的这段代码的输出如下:

[
  {
    "src1": {
      "table1": {},
      "table2": {}
    }
  },
  {
    "src2": {
      "table1": {},
    }
  }
]

我想要的输出:

[
  {
    "src1": {
      "table1": {
         "col1": {},
         "col2": {}
     },
      "table2": {
         "col1": {}
     }
    }
  },
  {
    "src2": {
      "table1": {
         "col1": {}
      }
    }
  }
]

如上所示将我的 2 层嵌套 JSON 文件转换为 3 层的任何帮助将不胜感激。提前谢谢你。

【问题讨论】:

    标签: python json pandas dataframe object


    【解决方案1】:

    由于您在这里有多个级别的分组,我建议您只使用 for 循环来迭代您的数据。

    from collections import defaultdict  
    
    def make_nested(df): 
        f = lambda: defaultdict(f)   
        data = f()  
    
        for row in df.to_numpy().tolist():
            t = data
            for r in row[:-1]:
                t = t[r]
            t[row[-1]] = {}
    
        return data
    

    print(json.dumps(make_nested(df), indent=2))
    {
      "src1": {
        "table1": {
          "col1": {},
          "col2": {}
        },
        "table2": {
          "col1": {}
        }
      },
      "src2": {
        "table1": {
          "col1": {},
          "col2": {}
        }
      }
    }
    

    这假设您的列从左到右排列:最外层键到最内层键。

    【讨论】:

    • 欣赏它。我也只需要前 3 列,因为我在 DataFrame 中也有其他列。您可以编辑答案以仅对前 3 列进行分组吗?谢谢
    • @weovibewvoibweoivwoiv 将 df[[col1, col2, col3]] 传递给函数,应该这样做。
    • 又发了一个后续问题,希望大家帮忙解答,谢谢。 stackoverflow.com/questions/60493133/…
    猜你喜欢
    • 2019-06-09
    • 2014-06-27
    • 1970-01-01
    • 2020-09-29
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 2021-12-29
    相关资源
    最近更新 更多