如何追加同键字典值并生成多行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
相关产品推荐
相关产品推荐

