gpt4 book ai didi

python - 将 Pandas Dataframe 或 csv 文件转换为自定义嵌套 JSON

转载 作者:行者123 更新时间:2023-12-05 07:03:54 25 4
gpt4 key购买 nike

我有一个带有 DF 的 csv 文件,其结构如下:

我的数据框:

enter image description here

我想使用python将数据输入为以下JSON格式。我查看了几个链接(但我在嵌套部分迷路了)。我检查的链接:

How to convert pandas dataframe to uniquely structured nested json

convert dataframe to nested json

"PHI": 2,
"firstname": "john",
"medicalHistory": {
"allergies": "egg",

"event": {
"inPatient":{
"hospitalized": {
"visit" : "7-20-20",
"noofdays": "5",
"test": {
"modality": "xray"
}
"vitalSign": {
"temperature": "32",
"heartRate": "80"

},
"patientcondition": {
"headache": "1",
"cough": "0"
}
},
"icu": {
"visit" : "",
"noofdays": "",
},
},
"outpatient": {
"visit":"5-20-20",
"vitalSign": {
"temperature": "32",
"heartRate": "80"
},
"patientcondition": {
"headache": "1",
"cough": "1"
},
"test": {
"modality": "blood"
}
}
}

}

如果有人可以帮助我处理嵌套数组,那将非常有帮助。

最佳答案

您需要一个或多个辅助函数来像这样解压表中的数据。编写主要辅助函数以接受两个参数:1.df 和 2.schema。该模式将用于将 df 解压缩为 df 中每一行的嵌套结构。下面的模式是如何为您描述的逻辑子集实现此目的的示例。虽然不完全是您在示例中指定的内容,但应该足以提示您自行完成其余任务。

from operator import itemgetter
groupby_idx = ['PHI', 'firstName']
groups = df.groupby(groupby_idx, as_index=False, drop=False)
schema = {
"event": {
"eventType": itemgetter('event'),
"visit": itemgetter('visit'),
"noOfDays": itemgetter('noofdays'),
"test": {
"modality": itemgetter('test')
},
"vitalSign": {
"temperature": itemgetter('temperature'),
"heartRate": itemgetter('heartRate')
},
"patientCondition": {
"headache": itemgetter('headache'),
"cough": itemgetter('cough')
}
}
}

def unpack(obj, schema):
tmp = {}
for k, v in schema.items():
if isinstance(v, (dict,)):
tmp[k] = unpack(obj, v)
if callable(v):
tmp[k] = v(obj)
return tmp

def apply_unpack(groups, schema):
results = {}
for gidx, df in groups:
events = []
for ridx, obj in df.iterrows():
d = unpack(obj, schema)
events.append(d)
results[gidx] = events
return results

unpacked = apply_unpack(groups, schema)

关于python - 将 Pandas Dataframe 或 csv 文件转换为自定义嵌套 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63082177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com