You need to enable JavaScript to run this app. 如何将嵌套列表中的嵌套字典结构数据转换为Pandas DataFrame
优惠活动
大模型
产品
解决方案
定价
更多

如何将嵌套列表中的嵌套字典结构数据转换为Pandas DataFrame

处理嵌套数据生成目标DataFrame解决方案

核心思路:通过逐层拆解嵌套结构,先拆分顶层字段,再分别处理字典型、列表型嵌套字段,最终把所有属性拆分为独立列。

完整实现代码

import pandas as pd

# 模拟你的原始数据结构,使用时替换为自己的真实数据即可
raw_data = [
    ['Asturias', {
        'Keyword': 'gato',
        'Related queries rising': {'query': 'No data', 'value': 0},
        'Related queries top': [{'query': 'el gato negro oviedo', 'value': 100}, {'query': 'gato precio asturias', 'value': 85}],
        'Related topics rising': {'topic_title': 'No data', 'topic_type': 'No data', 'value': 0},
        'Related topics top': [{'topic_title': 'Oviedo', 'topic_type': 'City', 'value': 100}, {'topic_title': 'Cat breed', 'topic_type': 'Category', 'value': 70}]
    }],
    ['Madrid', {
        'Keyword': 'gato',
        'Related queries rising': {'query': 'gato barato madrid', 'value': 230},
        'Related queries top': [{'query': 'gato persa madrid', 'value': 100}],
        'Related topics rising': {'topic_title': 'Pet adoption', 'topic_type': 'Service', 'value': 180},
        'Related topics top': [{'topic_title': 'Madrid', 'topic_type': 'City', 'value': 100}]
    }]
]

# 步骤1:生成初始DataFrame,拆分地区和信息列
df = pd.DataFrame(raw_data, columns=['地区', '信息'])

# 步骤2:拆解信息列的顶层字段,自动拆分字典类型的嵌套字段
df_info = pd.json_normalize(df['信息'])
df = pd.concat([df[['地区']], df_info], axis=1)

# 步骤3:处理列表类型的嵌套字段,先炸开再拆解内部字段
# 处理关联热门查询
df = df.explode('Related queries top', ignore_index=True)
df_top_query = pd.json_normalize(df['Related queries top']).add_prefix('关联热门查询.')
df = pd.concat([df.drop(columns=['Related queries top']), df_top_query], axis=1)

# 处理关联热门主题
df = df.explode('Related topics top', ignore_index=True)
df_top_topic = pd.json_normalize(df['Related topics top']).add_prefix('关联热门主题.')
df = pd.concat([df.drop(columns=['Related topics top']), df_top_topic], axis=1)

# 可选:重命名列名方便阅读
df = df.rename(columns={
    'Keyword': '关键词',
    'Related queries rising.query': '关联上升查询.query',
    'Related queries rising.value': '关联上升查询.value',
    'Related topics rising.topic_title': '关联上升主题.topic_title',
    'Related topics rising.topic_type': '关联上升主题.topic_type',
    'Related topics rising.value': '关联上升主题.value'
})

# 查看最终结果
print(df.head())

补充说明

  • 如果一个地区对应多个关键词,仅需在第一步新增explode关键词列的逻辑后再执行后续处理即可
  • 所有嵌套字段最终都会拆分为独立列,每个属性对应单独单元格,符合预期输出要求
  • 遇到'No data'的无效值可以后续用df.replace('No data', pd.NA)统一处理为缺失值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 14:06:06