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

如何将API返回的JSON解析后添加至已有Pandas DataFrame

需求实现方案

初始DataFrame结构

idtitleurls
1title1www.url1.com
2title2www.url2.com

需求说明

遍历每行调用API获取JSON数据,解析后将字段作为新列添加到原DataFrame中。示例的API调用逻辑如下:

for r in df:
    json_blob = make_api_call(r.urls)
    # take json blob and put into df?
    pd.read_json(json_blob)
    # add to row r back in the original df?

API返回的JSON结构示例:

{
  "validThrough": "2022-10-16",
  "description": "this and that",
  "Location": {
    "geo": {
      "longitude": "-73.962547",
      "latitude": "40.687089",
      "@type": "GeoCoordinates"
    }
  }
}

期望最终DataFrame结构

titleurlsvalidThroughdescriptionLocation.geo.longitudeLocation.geo.latitudeLocation.geo.@type
0title1www.url1.com2022-10-16this is a description-73.96254740.687089GeoCoordinates
n...

具体实现方法

方法1:使用apply结合json_normalize(推荐)

利用Pandas的apply处理每行数据,再通过json_normalize自动展开嵌套JSON结构,代码更简洁高效:

import pandas as pd

# 替换为你的真实API调用函数
def make_api_call(url):
    # 此处为模拟返回,实际改为API请求逻辑,比如requests.get(url).json()
    return {
        "validThrough": "2022-10-16",
        "description": f"description for {url}",
        "Location": {
            "geo": {
                "longitude": "-73.962547",
                "latitude": "40.687089",
                "@type": "GeoCoordinates"
            }
        }
    }

# 初始化初始DataFrame
df = pd.DataFrame({
    "id": [1, 2],
    "title": ["title1", "title2"],
    "urls": ["www.url1.com", "www.url2.com"]
})

# 调用API并将结果转为扁平化DataFrame
api_results = df["urls"].apply(lambda x: pd.json_normalize(make_api_call(x)))
api_df = pd.concat(api_results.to_list(), ignore_index=True)

# 合并原数据与API结果,移除不需要的id列
final_df = pd.concat([df.drop("id", axis=1), api_df], axis=1)

print(final_df)

方法2:使用循环遍历每行

如果更习惯循环写法,可按以下方式实现:

import pandas as pd

def make_api_call(url):
    # 模拟API返回,替换为真实请求逻辑
    return {
        "validThrough": "2022-10-16",
        "description": f"description for {url}",
        "Location": {
            "geo": {
                "longitude": "-73.962547",
                "latitude": "40.687089",
                "@type": "GeoCoordinates"
            }
        }
    }

df = pd.DataFrame({
    "id": [1, 2],
    "title": ["title1", "title2"],
    "urls": ["www.url1.com", "www.url2.com"]
})

# 存储每行API结果的列表
api_data = []
for _, row in df.iterrows():
    json_data = make_api_call(row["urls"])
    # 展开嵌套JSON并转为字典存入列表
    api_data.append(pd.json_normalize(json_data).iloc[0].to_dict())

# 转为DataFrame后合并到原数据
api_df = pd.DataFrame(api_data)
final_df = pd.concat([df.drop("id", axis=1), api_df], axis=1)

print(final_df)

关键注意事项

  • pd.json_normalize()是核心工具,自动将嵌套JSON转为扁平列,完美匹配需求中的列命名格式。
  • 实际使用时,需将make_api_call替换为真实API请求逻辑,比如用requests库发起请求并解析返回的JSON。
  • 建议添加异常处理(try-except块),避免API请求失败导致程序中断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:15:42