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

循环调用API获取数据时如何保留所有DataFrame而非仅最后一个

解决方法

方案1:用列表存储所有DataFrame

初始化一个空列表,每次循环把对应国家的DataFrame追加进去,最后可以一次性合并所有数据。

示例代码:

import pandas as pd
import requests

country_codes = ["ES", "EE", "LT"]
all_dfs = []  # 空列表用来存所有国家的DataFrame

for code in country_codes:
    # 这里替换成你的API请求逻辑
    response = requests.get(f"https://your-api-endpoint.com/country/{code}")
    raw_data = response.json()
    country_df = pd.DataFrame(raw_data)
    all_dfs.append(country_df)  # 将当前国家的DataFrame加入列表

# 合并所有DataFrame成一个大表
combined_df = pd.concat(all_dfs, ignore_index=True)

方案2:用字典存储(方便单独调用某国数据)

如果后续需要单独查看某个国家的数据,用字典更灵活——以国家代码为键,对应的DataFrame为值。

示例代码:

import pandas as pd
import requests

country_codes = ["ES", "EE", "LT"]
df_collection = {}  # 空字典存储数据

for code in country_codes:
    response = requests.get(f"https://your-api-endpoint.com/country/{code}")
    raw_data = response.json()
    df_collection[code] = pd.DataFrame(raw_data)  # 用国家代码做键存数据

# 合并所有DataFrame的话,直接取字典的值即可
combined_df = pd.concat(df_collection.values(), ignore_index=True)

原代码问题原因

你之前的代码应该是在循环里反复把结果赋值给同一个变量(比如df = pd.DataFrame(...)),每次循环都会覆盖掉之前的内容,所以循环结束后这个变量只保留最后一次(LT)的DataFrame。用列表或字典存储就能避免覆盖,留存所有国家的数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 20:24:51