点击查看代码
import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
# 读取数据
df = pd.read_excel('F:\python数学建模与算法\第九章习题\hm9.3.xlsx', header=None)
# 清理数据
df = df.apply(pd.to_numeric, errors='coerce') # 转换为数值型
df = df.dropna() # 删除包含 NaN 的行
# 绘制箱线图
fig = plt.figure()
ax = fig.add_subplot(111)
labels = ['Lab'+str(i) for i in range(1, 8)]
ax.boxplot(df.values, sym='xr', labels=labels)
plt.title('Boxplot of Labs')
plt.show()
# 准备数据进行线性回归
y = df.values.flatten() # 将 y 展平为一维数组
x = np.tile(np.arange(1, 8), (len(df), 1)).flatten() # 根据 df 的行数生成 x
# 创建模型字典
model_dic = {'x': x, 'y': y}
# 拟合线性回归模型
model = sm.formula.ols('y ~ C(x)', data=model_dic).fit()
# 进行 ANOVA 分析
anovat = sm.stats.anova_lm(model)
# 输出 ANOVA 结果
print(anovat)
![](https://img2024.cnblogs.com/blog/3513989/202411/3513989-20241126220542815-1789430746.png)
![](https://img2024.cnblogs.com/blog/3513989/202411/3513989-20241126220549571-746279175.png)
![](https://img2024.cnblogs.com/blog/3513989/202411/3513989-20241126220555062-1041055896.png)