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

面板回归代码报错求助:ValueError: Series仅支持二级多重索引

面板回归报错解决:ValueError: Series can only be used with a 2-level MultiIndex

问题描述

运行面板回归代码时触发错误:

mod = PooledOLS(df['debt'], exog)
pooled_res = mod.fit()
print(pooled_res)

错误信息:

ValueError: Series can only be used with a 2-level MultiIndex

原完整代码:

import pandas as pd
df=pd.read_excel(r"C:\Users\Action\Downloads\data.xlsx",8)
import matplotlib.pyplot as plt
import statsmodels.api as sm

# 设置外生/自变量
exog_vars = ["GDP", 'WTI']
exog = sm.add_constant(df[exog_vars])
print(exog.head(7))

# 设置内生/因变量
endog = df['debt']

# 导入linearmodels模块
import linearmodels
from linearmodels.panel import PooledOLS
from linearmodels import PanelOLS

# 运行模型(报错行)
mod = PooledOLS(df['debt'], exog)
pooled_res = mod.fit()
print(pooled_res)

错误原因

linearmodels库的PooledOLS及其他面板模型要求输入数据必须是标准面板格式——数据框必须包含个体(entity)和时间(time)的二级MultiIndex,用来区分不同横截面单元和时间观测值。当前数据未设置该二级索引,因此触发报错。

解决步骤

  1. 确认面板索引列:检查数据是否包含个体标识列(如企业ID、国家名称)和时间列(如年份、季度),假设这两列名为entity_id和year,替换为你数据中的实际列名。
  2. 设置二级MultiIndex:
# 替换为你数据中的个体列和时间列名
df = df.set_index(['entity_id', 'year'])
  1. 重新生成变量并运行模型:
# 基于带索引的df重新生成自变量和因变量
exog_vars = ["GDP", 'WTI']
exog = sm.add_constant(df[exog_vars])
endog = df['debt']

# 初始化并拟合模型
mod = PooledOLS(endog, exog)
pooled_res = mod.fit()
print(pooled_res)

补充说明

  • 若不确定数据中的个体/时间列,可先通过print(df.columns)查看所有列名,定位对应标识列。
  • 若数据原本不是面板格式(缺少个体或时间维度),需先整理数据,确保每个个体在不同时间点有观测值,再设置二级索引。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 08:45:36