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

如何将循环调用函数生成的多个DataFrame合并并导出为CSV?

问题描述

我写了一个f(name)函数,通过API分页获取数据并返回DataFrame。现在用循环传入不同的Account_ID调用这个函数,生成了10多个数据集,但直接导出的话只会保留最后一个结果。请问能不能把所有DataFrame合并后导出成CSV文件?

相关代码如下:
获取数据的函数:

def f(name):
        url = "https://apiurl"
        response = requests.get(url, params = {'page': 1}) 
        records = []
        for page_number in range(1, response.json().get("pages")+1):
            response = requests.get(url, params = {'page': page_number})
            records += response.json().get('records')
            df = pd.DataFrame(records)
        return df

循环调用的代码:

for row in valdf.itertuples():
    name = valdf.loc[row.Index, 'Account_ID']
    df1 = f(name)
    print(df1)
解决方案

当然可以,核心思路是先把每个循环生成的DataFrame存到一个列表里,最后一次性合并所有DataFrame再导出。

修改后的循环代码

# 创建空列表存储所有生成的DataFrame
all_dfs = []

for row in valdf.itertuples():
    name = valdf.loc[row.Index, 'Account_ID']
    df1 = f(name)
    all_dfs.append(df1)  # 将当前DataFrame加入列表
    print(df1)

# 合并所有DataFrame,ignore_index重置索引避免重复
combined_df = pd.concat(all_dfs, ignore_index=True)

# 导出为CSV文件,index=False不保存行索引
combined_df.to_csv('combined_account_data.csv', index=False)

额外优化建议

原函数f(name)存在两处可以优化的点:

  1. df = pd.DataFrame(records)放在循环内部会重复创建DataFrame,完全没必要,移到循环外即可;
  2. 原函数没有把name参数传入API请求的参数中,这大概率是疏漏——如果API需要Account_ID来区分数据,你得把它加到params里,否则所有请求都会返回同一个账号的数据。

优化后的函数代码:

def f(name):
        url = "https://apiurl"
        # 补充Account_ID参数到请求中,根据API实际字段名调整
        response = requests.get(url, params = {'page': 1, 'Account_ID': name}) 
        records = []
        # 增加默认值避免API返回的pages字段不存在时报错
        total_pages = response.json().get("pages", 1)
        for page_number in range(1, total_pages + 1):
            response = requests.get(url, params = {'page': page_number, 'Account_ID': name})
            # 增加默认空列表,避免records字段不存在时抛出异常
            records += response.json().get('records', [])
        # 循环结束后统一创建DataFrame
        df = pd.DataFrame(records)
        return df

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 00:06:26