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

如何从多个字典列表创建Pandas DataFrame并导出至Excel?

问题分析与解决

原代码的核心问题

  1. 数据处理逻辑错误:zip(gender, country_codes)仅会将两个列表的前2个元素配对(因gender只有2条数据),且直接把完整字典存入列中,未提取所需的字段值。
  2. DataFrame初始化参数错误:指定的columns=["name", "description"]与传入的字典数据不匹配,导致列中存储的是完整字典而非目标字段内容。
  3. rename方法使用错误:需通过columns参数明确列名映射关系,原代码未正确设置参数,无法完成列名修改。
  4. 数据长度不匹配:gender(2条)和country_codes(4条)长度不同,若要覆盖所有数据组合,需生成笛卡尔积而非简单配对。

正确实现代码

如果需要生成所有性别与国家编码的组合(共8行数据),可按以下方式实现:

import pandas as pd

country_codes = [
    {"id": 92, "name": "93", "position": 1, "description": "Afghanistan"},
    {"id": 93, "name": "355", "position": 2, "description": "Albania"},
    {"id": 94, "name": "213", "position": 3, "description": "Algeria"},
    {"id": 95, "name": "1-684", "position": 4, "description": "American Samoa"}
]

gender = [
   {"id": 1, "name": "Female"},
   {"id": 3, "name": "Male"}
]

# 提取所需字段
gender_values = [item["name"] for item in gender]
country_codes_values = [item["name"] for item in country_codes]
country_names = [item["description"] for item in country_codes]

# 生成所有性别与国家的组合(笛卡尔积)
df = pd.DataFrame([
    [g, cc, cn]
    for g in gender_values
    for cc, cn in zip(country_codes_values, country_names)
], columns=["Gender", "Country Code", "Country Name"])

# 导出到Excel
with pd.ExcelWriter('my_excel_file.xlsx', engine='xlsxwriter') as writer:
    df.to_excel(writer, sheet_name="sample_sheet", index=False)

代码说明

  • 字段提取:从字典列表中直接取出需要的Gender、Country Code和Country Name字段值,避免存储无用的字典结构。
  • 笛卡尔积生成:通过嵌套循环生成所有性别与国家的组合,确保所有数据都被包含进DataFrame。
  • Excel导出:使用with语句管理ExcelWriter,自动处理文件的打开与关闭,避免资源泄漏。

如果仅需要按两个列表的最短长度配对(仅前2条国家数据对应性别),可使用简化代码:

import pandas as pd

# 提取字段并按长度配对
df = pd.DataFrame({
    "Gender": [item["name"] for item in gender],
    "Country Code": [item["name"] for item in country_codes[:len(gender)]],
    "Country Name": [item["description"] for item in country_codes[:len(gender)]]
})

with pd.ExcelWriter('my_excel_file.xlsx', engine='xlsxwriter') as writer:
    df.to_excel(writer, sheet_name="sample_sheet", index=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:40:23