python - 根据一列中的值创建 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"
}
}
}
解决方案
让我尝试一下:
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'
}}}
推荐阅读
- java - WiFi P2P Communication(Already Connected Devices)
- javascript - Javascript - 如何从 json 文件中获取数据?
- spring-boot - 如何配置 Zuul 一个微服务的多个实例
- python - 如何将数字插入正则表达式
- webpack - 如何从 Webpack 4 中的单个 JS 文件输出多个 CSS 文件?
- c++ - 在 do-while 循环中初始化字符串将在检查条件之前跳转到它
- css - 停止在智能手机上滚动时删除“图像缩放”效果
- javascript - 如何在Javascript中将数字数组转换为整数
- node.js - 使用 Nodejs 调用需要证书的 SOAP 服务
- php - php联系表格,是否可以检查是否收到了自动电子邮件?