如何使用熊猫将Excel文件转换为嵌套JSON?

我是一名菜鸟程序员,我正在尝试使用Pandas将Excel文件转换为嵌套JSON。

我正在发布我的代码和预期的输出,到目前为止我还无法实现。问题是,我转换为嵌套信息的excel列实际上应该属于“地址”名称,而我不知道该怎么做。感谢您的任何建议。

这是excel文件的外观:

如何使用熊猫将Excel文件转换为嵌套JSON?

import pandas as pd
import json

df = pd.read_excel("...",encoding = "utf-8-sig")
df.fillna('',inplace = True)

def get_nested_entry(key,grp):
    entry = {}
    entry['Forename'] = key[0]
    entry['Middle Name'] = key[1]
    entry['Surname'] = key[2]

    for field in ['Address - Country']:
        entry[field] = list(grp[field].unique())
    return entry

entries = []
for key,grp in df.groupby(['Forename','Middle Name','Surname']):
    entry = get_nested_entry(key,grp)
    entries.append(entry)

print(entries)
with open("excel_to_json_output.json","w",encoding = "utf-8-sig") as f:
    json.dump(entries,f,indent = 4)    

这是预期的结果

 [
        {
            "firstName": "Angela","lastName": "L.","middleName": "Johnson","addresses": [
                {
                    "postcode": "32807","city": "Orlando","state": "FL","country": "United States of America"
                }
            ],

我得到的是这个

[
    {
        "Forename": "Angela","Middle Name": "L.","Surname": "Johnson","Address - Country": [
            "United States of America"
        ]
    },
huyang1644 回答:如何使用熊猫将Excel文件转换为嵌套JSON?

尝试一下

b = {'First_Name': ["Angela","Peter","John"],'Middle_Name': ["L","J","A"],'Last_Name': ["Johnson","Roth","Williams"],'City': ["chicago","seattle","st.loius"],'state': ["IL","WA","MO"],'zip': [60007,98105,63115],'country': ["USA","USA","USA"]}

df = pd.DataFrame(b)

predict = df.iloc[:,:3].to_dict(orient='records')
postdict = df.iloc[:,3:].to_dict(orient='records')
entities=[]
for i in range(df.shape[0]):
    tm = predict[i]
    tm["addresses"] = [postdict[i]]
    entities.append(tm)

输出

[{'First_Name': 'Angela','Middle_Name': 'L','Last_Name': 'Johnson','addresses': [{'City': 'chicago','state': 'IL','zip': 60007,'country': 'USA'}]},{'First_Name': 'Peter','Middle_Name': 'J','Last_Name': 'Roth','addresses': [{'City': 'seattle','state': 'WA','zip': 98105,{'First_Name': 'John','Middle_Name': 'A','Last_Name': 'Williams','addresses': [{'City': 'st.loius','state': 'MO','zip': 63115,'country': 'USA'}]}]
本文链接:https://www.f2er.com/3124839.html

大家都在问