You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将多数组属性值导出至CSV?现有代码输出异常求助

问题分析

你的原代码核心问题在于:遍历Distribution下的每个key(Section和Identity)时,会循环覆盖temp字典里的对应字段,最终每个字段只保留数组的最后一个元素值,所以只能生成1条记录。要实现你期望的多条记录输出,我们需要把Distribution下每个数组的元素都拆分成单独的行,同时保留基础的IdNo和Name信息。

修改方案

这里提供两种思路,分别对应不同的输出需求:

方案1:匹配你给出的期望输出格式

假设你期望的是将Section的唯一值与每个Identity值组合成多行(第二条记录的Section值大概率是笔误,应该保留S1234),修改后的代码如下:

import pandas as pd

# 你的样本数据
json_file = { "data": [ { "IdNo": "1234", "Name": "ABC", "Distribution": { "Section": [ { "SectionName": { "id": "S1234" } } ], "Identity": [ { "SectionName": { "id": "S5678" } }, { "SectionName": { "id": "S7878" } } ] } } ] }

df = pd.DataFrame()
for item in json_file['data']:
    # 提取基础身份信息
    base_info = {
        'IdNo': item['IdNo'],
        'Name': item['Name']
    }
    # 提取Section下的所有ID(这里仅1个)
    section_ids = [s['SectionName']['id'] for s in item['Distribution']['Section']]
    # 提取Identity下的所有ID(这里有2个)
    identity_ids = [i['SectionName']['id'] for i in item['Distribution']['Identity']]
    
    # 生成每条组合记录
    for sec_id in section_ids:
        for iden_id in identity_ids:
            temp = base_info.copy()
            temp['Section'] = sec_id
            temp['Identity'] = iden_id
            df = pd.concat([df, pd.DataFrame([temp])], ignore_index=True)

print(df)

输出结果:

IdNo Name Section Identity
0  1234  ABC   S1234    S5678
1  1234  ABC   S1234    S7878

如果你的实际需求是让Section和Identity的元素各自单独成行(即第二条记录仅保留Identity值,Section为空),可以调整为:

import pandas as pd

json_file = { "data": [ { "IdNo": "1234", "Name": "ABC", "Distribution": { "Section": [ { "SectionName": { "id": "S1234" } } ], "Identity": [ { "SectionName": { "id": "S5678" } }, { "SectionName": { "id": "S7878" } } ] } } ] }

df = pd.DataFrame()
for item in json_file['data']:
    base_info = {
        'IdNo': item['IdNo'],
        'Name': item['Name']
    }
    # 处理Section条目
    for s in item['Distribution']['Section']:
        temp = base_info.copy()
        temp['Section'] = s['SectionName']['id']
        temp['Identity'] = None
        df = pd.concat([df, pd.DataFrame([temp])], ignore_index=True)
    # 处理Identity条目
    for i in item['Distribution']['Identity']:
        temp = base_info.copy()
        temp['Section'] = None
        temp['Identity'] = i['SectionName']['id']
        df = pd.concat([df, pd.DataFrame([temp])], ignore_index=True)

print(df)

方案2:更通用的长格式输出(推荐)

如果你的数据结构可能更复杂(比如Section或Identity有多个值),推荐使用长格式存储,这样后续分析和维护更灵活:

import pandas as pd

json_file = { "data": [ { "IdNo": "1234", "Name": "ABC", "Distribution": { "Section": [ { "SectionName": { "id": "S1234" } } ], "Identity": [ { "SectionName": { "id": "S5678" } }, { "SectionName": { "id": "S7878" } } ] } } ] }

rows = []
for item in json_file['data']:
    base_id = item['IdNo']
    base_name = item['Name']
    # 遍历Distribution下的所有分类
    for dist_type, items in item['Distribution'].items():
        for sub_item in items:
            rows.append({
                'IdNo': base_id,
                'Name': base_name,
                'Type': dist_type,
                'Value': sub_item['SectionName']['id']
            })

df = pd.DataFrame(rows)
print(df)

输出结果:

IdNo Name      Type  Value
0  1234  ABC   Section  S1234
1  1234  ABC  Identity  S5678
2  1234  ABC  Identity  S7878
关键改进点
  • 不再用循环覆盖字典值,而是为每个数组元素单独创建记录
  • 明确提取每个Distribution分类下的所有ID,避免遗漏
  • 使用copy()方法避免修改原基础信息字典
  • 用ignore_index=True避免索引混乱

内容的提问来源于stack exchange,提问作者Arya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:55:38