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

如何用Pandas扁平化嵌套JSON数据并提取指定嵌套字段

处理OpenAQ API嵌套JSON数据的解决方案

1. 基础数据获取与初始展开

先确认你已经完成了API调用和results字段的展开,代码示例如下:

import requests
import pandas as pd

# 调用OpenAQ API(示例接口,可根据需求调整参数)
resp = requests.get("https://api.openaq.org/v2/latest?country=CN&limit=20")
raw_data = resp.json()

# 展开results字段得到初始DataFrame
df = pd.json_normalize(raw_data["results"])

2. 拆分嵌套的parameters列

parameters是包含多个参数对象的列表,可根据需求选择以下处理方式:

  • 多参数分行保留原字段:如果希望每个参数单独占一行,同时保留原记录的其他信息
# 将parameters列表拆分为多行
df_exploded = df.explode("parameters", ignore_index=True)
# 拆分嵌套的参数字段为独立列
df_params = pd.json_normalize(df_exploded["parameters"])
# 合并回原DataFrame
df_final = pd.concat([df_exploded.drop("parameters", axis=1), df_params], axis=1)
  • 单参数直接提取字段:如果每个记录仅包含一个参数
# 提取parameters列表中第一个对象的字段为新列
df[["parameter", "value", "unit", "lastUpdated"]] = df["parameters"].apply(
    lambda x: pd.Series(x[0]) if x else pd.Series([None]*4)
)
# 删除原parameters列
df.drop("parameters", axis=1, inplace=True)

3. 拆分sources列并提取url字段

sources同样是嵌套列表对象,以下是针对性处理方案:

单独提取url字段

  • 提取第一个数据源的url作为独立列:
df["source_url"] = df["sources"].apply(lambda x: x[0]["url"] if x else None)
  • 合并所有数据源的url(用逗号分隔):
df["all_source_urls"] = df["sources"].apply(lambda x: ",".join([s["url"] for s in x]) if x else None)

完整拆分sources列

如果需要把sources的所有字段都拆分为独立列:

df_sources_exploded = df.explode("sources", ignore_index=True)
df_sources = pd.json_normalize(df_sources_exploded["sources"])
df_final = pd.concat([df_sources_exploded.drop("sources", axis=1), df_sources], axis=1)

注意事项

  • 部分记录可能存在sources或parameters为空列表的情况,处理时需加判断避免报错
  • 可根据实际需求调整API请求参数(比如country、limit、parameter等)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 06:45:56