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

按国家唯一ID拆分面板数据后循环绘图与执行回归的实现方法

解决方案

前置说明

不推荐你当前用locals()动态生成df1到df142变量的做法,容易出现变量冲突,且不好管理。下面会给两种实现方案:一种是适配你已经生成好独立子数据集的场景,另一种是更高效的直接基于分组结果处理的方案(不需要提前拆分数据集)。

方案1:适配已生成df1~df142的场景

首先导入依赖库:

import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.formula.api as smf # 用于统计回归分析,可根据你的需求替换为其他回归工具
# 配置中文绘图显示,不需要可删除
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

循环处理所有国家数据集的代码如下:

# 你需要分析的宏观变量列表,根据实际情况修改
target_cols = ['x1', 'x2']
# 回归公式,根据你的分析需求修改,示例为x1作为被解释变量,year和x2作为解释变量
reg_formula = 'x1 ~ year + x2'

for i in range(1, 143):
    country_df = locals()[f'df{i}']
    country_id = country_df['ID'].iloc[0]
    # 跳过样本量不足的国家,避免回归报错,阈值根据你的变量数量调整
    if len(country_df) < 3:
        print(f"国家{country_id}样本量不足,跳过处理")
        continue
    
    # ========== 1. 绘制单个变量时序图 ==========
    for col in target_cols:
        plt.figure(figsize=(10, 6))
        plt.plot(country_df['year'], country_df[col], marker='o', linewidth=2)
        plt.title(f"国家{country_id} {col} 时序变化")
        plt.xlabel('年份')
        plt.ylabel(col)
        plt.grid(alpha=0.3)
        # 保存图片到本地,不需要保存可替换为plt.show()直接显示
        plt.savefig(f"{country_id}_{col}_时序图.png", dpi=300, bbox_inches='tight')
        plt.close() # 关闭画布避免内存溢出
    
    # ========== 2. 执行单国家回归分析 ==========
    model = smf.ols(formula=reg_formula, data=country_df).fit()
    # 打印回归结果,也可以提取关键指标存入汇总表统一管理
    print(f"================= 国家{country_id} 回归结果 =================")
    print(model.summary())
    print("\n")

方案2:更推荐的分组直接处理方案(无需提前拆分子数据集)

你不需要提前把原数据集拆成142个独立DataFrame,直接在groupby循环里处理即可,代码更简洁,也不会产生大量冗余变量:

import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.formula.api as smf

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

target_cols = ['x1', 'x2']
reg_formula = 'x1 ~ year + x2'

# 直接循环分组结果,不需要提前生成df1~df142
for country_id, country_df in dfx.groupby('ID'):
    if len(country_df) < 3:
        print(f"国家{country_id}样本量不足,跳过处理")
        continue
    
    # 时序图绘制逻辑和方案1完全一致
    for col in target_cols:
        plt.figure(figsize=(10, 6))
        plt.plot(country_df['year'], country_df[col], marker='o', linewidth=2)
        plt.title(f"国家{country_id} {col} 时序变化")
        plt.xlabel('年份')
        plt.ylabel(col)
        plt.grid(alpha=0.3)
        plt.savefig(f"{country_id}_{col}_时序图.png", dpi=300, bbox_inches='tight')
        plt.close()
    
    # 回归分析逻辑和方案1完全一致
    model = smf.ols(formula=reg_formula, data=country_df).fit()
    print(f"================= 国家{country_id} 回归结果 =================")
    print(model.summary())
    print("\n")

补充说明

  • 如果需要做单变量的时间趋势回归,修改reg_formula即可,比如x1对年份回归写为'x1 ~ year'
  • 如果需要批量留存回归结果,可以提取每个模型的系数、p值、R方等指标存入一个汇总DataFrame,方便后续批量分析
  • 若不需要保存图片到本地,把plt.savefig替换为plt.show()即可直接弹窗显示图表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:45:02