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

如何高效将嵌套字典列表转换为DataFrame单行?

处理嵌套比赛统计数据的Pythonic方案

核心思路

借助Pandas内置的结构化数据处理工具,直接展开嵌套字典列表,避免手动逐个提取字段的冗余操作,同时保证批量处理的效率。

实现步骤

1. 先明确API返回的典型数据结构

# 示例API返回数据(你的实际数据结构可对应调整)
sample_match = {
    "match_id": 123,
    "match_date": "2024-05-20",
    "teams": [
        {"side": "home", "stats": {"goals": 2, "shots": 10, "possession": 55}},
        {"side": "away", "stats": {"goals": 1, "shots": 8, "possession": 45}}
    ]
}

2. 轻量循环实现(适合新手理解)

import pandas as pd

def flatten_single_match(match):
    # 提取非嵌套的基础字段
    base_data = {k: v for k, v in match.items() if k != "teams"}
    # 遍历主客场数据,给统计字段加前缀后合并
    for team in match["teams"]:
        side_prefix = team["side"]
        stats = {f"{side_prefix}_{stat}": val for stat, val in team["stats"].items()}
        base_data.update(stats)
    return base_data

# 批量处理250+场比赛
all_matches = [sample_match]  # 替换为你的API返回数据列表
final_df = pd.DataFrame([flatten_single_match(m) for m in all_matches])

3. 高效Pandas原生实现(适合大数据量)

用json_normalize+透视表组合,减少Python循环开销:

import pandas as pd

# 直接展开嵌套的teams字段
normalized_df = pd.json_normalize(
    all_matches,
    record_path="teams",
    meta=["match_id", "match_date"],
    sep="_"
)

# 透视转宽表,单场比赛对应一行
wide_df = normalized_df.pivot(
    index=["match_id", "match_date"],
    columns="side",
    values=[col for col in normalized_df.columns if col not in ["match_id", "match_date", "side"]]
).reset_index()

# 清理列名,去除层级结构
wide_df.columns = ["_".join(col).strip("_") for col in wide_df.columns.values]

方案优势

  • 无需硬编码统计字段,新增指标时无需修改代码
  • 利用Pandas底层优化,比纯Python循环处理速度更快
  • 代码结构简洁,符合Pythonic的可读性要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 12:42:35