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

如何通过循环等方式将列表传入reporter参数并合并为单个DataFrame

实现代码

import pandas as pd
import world_trade_data as wits    
pd.set_option('display.max_rows', 6)

# 定义待查询的国家列表
country_list = ['arg','AFG','ALB','DZA']
# 临时存储每个国家返回的数据集
df_storage = []

# 遍历国家列表逐次调用接口
for country_code in country_list:
    country_import = wits.get_indicator(
        'MPRT-TRD-VL', 
        reporter=country_code, 
        year='all',
        partner='wld',
        datasource='tradestats-trade',
        name_or_id='name'
    )
    df_storage.append(country_import)

# 合并所有国家的查询结果为同一个DataFrame
total_import_df = pd.concat(df_storage, ignore_index=True)

补充说明

  • 用列表暂存各国家的查询结果,比循环中直接拼接DataFrame的性能更高,适合查询国家数量多的场景
  • pd.concat参数ignore_index=True会重置合并后数据集的行索引,避免不同国家的返回结果出现索引重复冲突
  • 如果需要处理接口调用超时、无返回数据等异常情况,可以在循环中加入异常捕获逻辑,示例如下:
for country_code in country_list:
    try:
        country_import = wits.get_indicator(
            'MPRT-TRD-VL', 
            reporter=country_code, 
            year='all',
            partner='wld',
            datasource='tradestats-trade',
            name_or_id='name'
        )
        df_storage.append(country_import)
    except Exception as e:
        print(f"国家{country_code}数据查询失败,错误信息:{e}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:39:03