首页 > 解决方案 > 根据一列中的值创建 json 文件

问题描述

我有一个包含多个列的数据框,我想将其转换为 .json 文件。.json 文件的结构应该是这样的:我想使用一列作为“标识符”列,其中的值用作字典的键。此列中的所有值都是唯一的。所有其他列应按出现顺序表示为标识符列的每个唯一值的键值映射。我也在寻找一个函数来重现基于这个 .json 文件的数据框。这是一个生成虚拟数据帧的示例代码:

import numpy as np
import pandas as pd

data_dictionary = {'col_1':[np.nan,np.nan,np.nan,np.nan],
                   'col_2':[np.nan,1,np.nan,1],
                   'col_3':['a','b','c','d'],
                   'col_4':['description of a','description of b','description of c','description of d']}

df = pd.DataFrame(data_dictionary)

这使:

   col_1  col_2 col_3             col_4
0    NaN    NaN     a  description of a
1    NaN    1.0     b  description of b
2    NaN    NaN     c  description of c
3    NaN    1.0     d  description of d

这就是 .json 文件的样子(使用 col_3 作为标识符列):

{
  "col_3": {
    "a": {
      "col_1": null,
      "col_2": null,
      "col_4": "description of a"
    },
    "b": {
      "col_1": null,
      "col_2": 1,
      "col_4": "description of b"
    },
    "c": {
      "col_1": null,
      "col_2": null,
      "col_4": "description of c"
    },
    "d": {
      "col_1": null,
      "col_2": 1,
      "col_4": "description of d"
    }
  }
}

标签: pythonjsonpandas

解决方案


让我尝试一下:

import json
dict_result = df.set_index('col_3').to_json(orient='index')
final = {'col_3':json.loads(dict_result)}
print(final)

>>>{'col_3': 
     {'a': 
        {
         'col_1': None,
         'col_2': None,
         'col_4': 'description of a'
        }, 
      'b': 
        {
         'col_1': None, 
         'col_2': 1.0, 
         'col_4': 'description of b'
        }, 
      'c': 
        { 
         'col_1': None, 
         'col_2': None,
         'col_4': 'description of c'
        }, 
     'd': 
        {
         'col_1': None,
         'col_2': 1.0,
         'col_4': 'description of d'
 }}}

推荐阅读