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

使用statsmodels构建OLS模型时出现PatsyError问题求助

解决statsmodels OLS模型列名带空格的报错问题

方法1:在公式中用反引号包裹带空格的列名

statsmodels依赖的patsy库允许用反引号包裹含特殊字符(比如空格)的变量名,直接修正公式即可:

import statsmodels.formula.api as smf
# 给带末尾空格的列名添加反引号
model = smf.ols(formula='`Life_expectancy ` ~ BMI', data=x_train).fit()
print(model.summary())

方法2:提前清理数据列名(更推荐)

直接去除所有列名的首尾空格,从根源避免后续操作再踩同类坑:

import statsmodels.formula.api as smf
# 批量清理列名的首尾空格
x_train.columns = x_train.columns.str.strip()
# 使用清理后的标准列名构建模型
model = smf.ols(formula='Life_expectancy ~ BMI', data=x_train).fit()
print(model.summary())

内容的提问来源于stack exchange,提问作者Amelia Putri Damayanti

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 05:57:36