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

如何基于不同长度字典进行单因素ANOVA分析?

不等样本量ANOVA分析:基于不等长字典的处理方案

你手头有一组不等长的分组实验数据:

data = {'treatment_1': [80, 0, 0, 8],
        'treatment_2': [78, 62],
        'treatment_3': [85, 62, 10, 3, 18, 18, 98, 71, 78, 12, 52, 39, 24, 13],
        'treatment_4': [78, 33, 78, 40, 47, 32]
       }

直接用pd.DataFrame(data)生成DataFrame时会触发报错:

ValueError: All arrays must be of the same length

这是因为Pandas默认生成的是宽格式表,要求所有列长度一致,但ANOVA分析需要的是长格式数据(一列存分组标签,一列存对应样本值),所以不用硬凑等长,转成合适的格式即可。


1. 将不等长字典转成长格式DataFrame

遍历字典,把每个样本的分组标签和数值配对,构建长格式数据:

import pandas as pd

data = {'treatment_1': [80, 0, 0, 8],
        'treatment_2': [78, 62],
        'treatment_3': [85, 62, 10, 3, 18, 18, 98, 71, 78, 12, 52, 39, 24, 13],
        'treatment_4': [78, 33, 78, 40, 47, 32]
       }

# 构建长格式数据列表
long_format_data = []
for treatment_name, values in data.items():
    for val in values:
        long_format_data.append({'分组': treatment_name, '数值': val})

# 转换成DataFrame
df = pd.DataFrame(long_format_data)

生成的长格式表每行对应一个样本,完全满足ANOVA的输入要求。


2. 执行ANOVA分析

这里提供两种常用的实现方式:

方式一:使用scipy.stats快速计算

提取每个分组的数值列表,调用f_oneway直接得到F统计量和P值:

from scipy.stats import f_oneway

# 提取各分组数值
group1 = df[df['分组'] == 'treatment_1']['数值']
group2 = df[df['分组'] == 'treatment_2']['数值']
group3 = df[df['分组'] == 'treatment_3']['数值']
group4 = df[df['分组'] == 'treatment_4']['数值']

# 执行ANOVA
f_statistic, p_value = f_oneway(group1, group2, group3, group4)
print(f"F统计量: {f_statistic:.4f}, P值: {p_value:.4f}")

方式二:使用statsmodels生成完整方差分析表

这种方式会输出包含自由度、平方和、均方等的详细统计结果,更适合专业分析:

import statsmodels.api as sm
from statsmodels.formula.api import ols

# 拟合方差分析模型
model = ols('数值 ~ C(分组)', data=df).fit()
anova_result = sm.stats.anova_lm(model, typ=2)
print(anova_result)

关于字典存储的疑问

字典完全适合存储这种不等长分组数据,它能清晰关联分组名称和对应样本集合。你之前的问题只是选错了DataFrame的格式(宽格式不支持不等长),转成长格式后就可以正常用于分析,不需要更换存储方式。

内容的提问来源于stack exchange,提问作者jason-hernandez-73

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:39:22