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

如何完整打印ndarray信息并让statsmodels OLS输出保留DataFrame列名

问题根源

你在代码中使用.values将DataFrame转换为纯数值ndarray时,丢失了原有特征列名信息,导致statsmodels拟合结果无法关联展示对应特征名。

最优解决方案

直接传入DataFrame而非ndarray进行拟合,statsmodels会自动保留列名信息,修改后代码如下:

import pandas
import statsmodels.api as statmodel
df = pandas.read_csv('fastfood.csv')

df = df[['total_fat', 'sat_fat', 'cholesterol', 'sodium','calories']]
# 去掉.values调用,保留DataFrame的列名属性
X = df[['total_fat', 'sat_fat', 'cholesterol', 'sodium']]
Y = df['calories']
# add_constant会自动给新增的截距项命名为const,保留原有特征列名
X = statmodel.add_constant(X)
model = statmodel.OLS(Y, X).fit()

print(model.mse_total.round(2))
print(model.rsquared.round(2))
print(model.params.round(2))
print(model.pvalues.round(2))

修改后model.params和model.pvalues会自动变为带特征名索引的Series,输出格式和你预期的一致。

备选方案(必须使用ndarray的场景)

如果你的业务逻辑需要提前将特征转换为ndarray做其他处理,可以在输出前手动为参数绑定列名:

# 在fit()之后、print()之前添加如下代码
feature_names = ['const', 'total_fat', 'sat_fat', 'cholesterol', 'sodium']
model.params = pandas.Series(model.params, index=feature_names)
model.pvalues = pandas.Series(model.pvalues, index=feature_names)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 15:48:05