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

如何追加同键字典值并生成多行Pandas DataFrame?

解决方案

核心思路是用列表存储多个邮编对应的字典数据,再将整个列表传入pd.DataFrame(),就能自动生成包含多行数据的DataFrame。

具体实现步骤

  • 封装获取单个邮编数据的函数,减少重复代码
  • 定义需要查询的邮编列表
  • 遍历列表,逐个调用API获取数据并追加到列表中
  • 用这个列表生成多行DataFrame

示例代码

import requests
import pandas as pd

def get_postcode_data(postcode):
    url = f"https://api.getthedata.com/postcode/{postcode}"
    req = requests.get(url)
    data = req.json()
    return data["data"]

# 要查询的邮编集合
postcodes = ["ST87HL", "SW1A1AA"]

# 存储所有邮编数据的列表
all_entries = []
for postcode in postcodes:
    entry = get_postcode_data(postcode)
    all_entries.append(entry)

# 生成多行结构的DataFrame
df = pd.DataFrame(all_entries)
print(df)

如果后续需要追加更多邮编数据,只需往postcodes列表里添加新邮编,重新执行遍历逻辑即可,新数据会自动成为DataFrame的新行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 23:40:38