用于在可以更改组的不同数据框中执行方差分析的代码。 Python

问题描述 投票:0回答:1

我有以下数据框。但是,它可以是该格式的任何数据帧。

df = pd.DataFrame({'Weight': [4.17,5.58,5.18,6.11,4.5,4.61,5.17,4.53,5.33,5.14,4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69,6.31,5.12,5.54,5.5,5.37,5.29,4.92,6.15,5.8,5.26],
                   'Group': ['A','A','A','A','A','A','A','A','A','A','B','B','B','B','B','B','B','B','B','B','C','C','C','C','C','C','C','C','C','C'] 
                   })

print(df)

我如何执行方差分析以为此提供F和p值,而无需通过文本明确指定组。换句话说,有没有代码可以自动检测组并运行ANOVA,以便它可以在该结构中的任何数据帧上工作。不只是这个。

非常感谢!

python pandas dataframe scipy anova
1个回答
0
投票

为了测试组的每个组合之间均值的相似性,我们可以使用itertools.combinationsscipy.stats.f_oneway

from itertools import product, combinations
from scipy.stats import f_oneway

combs = list(combinations(df['Group'].unique(), 2))
for g1, g2 in combs:
    a = f_oneway(df.loc[df['Group'] == g1, 'Weight'], 
                 df.loc[df['Group'] == g2, 'Weight'])
    print(f'For groups {g1} & {g2} the F-value is: {a[0]}, the p-value is: {a[1]}')

输出

For groups A & B the F-value is: 1.4191012973623165, the p-value is: 0.24902316597300575
For groups A & C the F-value is: 4.554043294351827, the p-value is: 0.04685138491157386
For groups B & C the F-value is: 9.0606932332992, the p-value is: 0.007518426118219876
© www.soinside.com 2019 - 2024. All rights reserved.