Dataframe 到JSON的转换

6jjcrrmo  于 2023-02-10  发布在  其他
关注(0)|答案(1)|浏览(113)

我想将 Dataframe 从这种格式转换为JSON

    • 数据框架表**

| 区域|省|自治市|巴兰盖|
| - ------|- ------|- ------|- ------|
| 区域1|省1|市1|镇1|
| 区域1|省1|市1|镇2|
| 区域1|省1|市2|镇3|
| 区域1|省1|市2|4镇|
| 区域1|省2|第三自治市|5镇|
| 区域1|省2|第三自治市|镇6|
| 区域1|省2|第四自治市|镇7|
| 区域1|省2|第四自治市|镇8|

    • JSON格式:**
regions = [
  {
    name: 'Region 1',
    provinces: [
      {
        name: 'Province 1',
        municipalities: [
          {
            name: 'Municipality 1',
            barangays: [
              'Barangay 1',
              'Barangay 2',
              // Add more barangays here
            ]
          },
          {
            name: 'Municipality 2',
            barangays: [
              'Barangay 3',
              'Barangay 4',
              // Add more barangays here
            ]
          },
          // Add more municipalities here
        ]
      },
      {
        name: 'Province 2',
        municipalities: [
          {
            name: 'Municipality 3',
            barangays: [
              'Barangay 5',
              'Barangay 6',
              // Add more barangays here
            ]
          },
          {
            name: 'Municipality 4',
            barangays: [
              'Barangay 7',
              'Barangay 8',
              // Add more barangays here
            ]
          },
          // Add more municipalities here
        ]
      },
      // Add more provinces here
    ]
  }
  // Add more regions here
];

我尝试了df.to_json(orient="records")。我尝试了splitrecordsindexcolumnsvaluestable参数,但不是我需要的方式。它将用于表单中的依赖下拉列表。

ulydmbyx

ulydmbyx1#

据我所知,原生的panda函数不提供这种类型的细分,但是可以用groupby遍历地区、省和市,然后手动构建一个字典(然后可以用类似json.dumps的代码将其翻译成json

out = []
for region, region_data in df.groupby("Region"):
    region_dct = {"name": region, "provinces": []}
    for province, province_data in region_data.groupby("Province"):
        province_dct = {"name": province, "municipalities": []}
        for municipality, municipality_data in province_data.groupby("Municipality"):
            municipality_dct = {"name": municipality, "barangays": municipality_data["Barangay"].tolist()}
            province_dct["municipalities"].append(municipality_dct)
        region_dct["provinces"].append(province_dct)
    out.append(region_dct)
print(out)
[{'name': 'Region 1',
  'provinces': [{'municipalities': [{'barangays': ['Barangay 1', 'Barangay 2'],
                                     'name': 'Municipality 1'},
                                    {'barangays': ['Barangay 3', 'Barangay 4'],
                                     'name': 'Municipality 2'}],
                 'name': 'Province 1'},
                {'municipalities': [{'barangays': ['Barangay 5', 'Barangay 6'],
                                     'name': 'Municipality 3'},
                                    {'barangays': ['Barangay 7', 'Barangay 8'],
                                     'name': 'Municipality 4'}],
                 'name': 'Province 2'}]}]

相关问题