进行2个样本t检验

发布于 2021-01-29 15:08:13

我有一个平均值,分别是样本1和样本2的标准差和n-样本是从样本总体中提取的,但是是由不同的实验室进行测量的。

样本1和样本2的n不同。我想进行加权(考虑n)两尾t检验。

我尝试通过创建带有scipy.stat的模块来使用scipy.stat模块np.random.normal,因为该模块仅获取数据,而不获取诸如mean和std
dev之类的stat值(可以直接使用这些值)。但这没有用,因为数据数组必须大小相等。

对于如何获得p值的任何帮助将不胜感激。

关注者
0
被浏览
102
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    如果您将原始数据作为数组ab,则可以使用scipy.stats.ttest_ind参数equal_var=False

    t, p = ttest_ind(a, b, equal_var=False)
    

    如果只有两个数据集的摘要统计信息,则可以使用scipy.stats.ttest_ind_from_stats(在0.16版中添加到scipy中)或通过公式(http://en.wikipedia.org/wiki/Welch%27s_t_test)计算t值。

    以下脚本显示了可能性。

    from __future__ import print_function
    
    import numpy as np
    from scipy.stats import ttest_ind, ttest_ind_from_stats
    from scipy.special import stdtr
    
    np.random.seed(1)
    
    # Create sample data.
    a = np.random.randn(40)
    b = 4*np.random.randn(50)
    
    # Use scipy.stats.ttest_ind.
    t, p = ttest_ind(a, b, equal_var=False)
    print("ttest_ind:            t = %g  p = %g" % (t, p))
    
    # Compute the descriptive statistics of a and b.
    abar = a.mean()
    avar = a.var(ddof=1)
    na = a.size
    adof = na - 1
    
    bbar = b.mean()
    bvar = b.var(ddof=1)
    nb = b.size
    bdof = nb - 1
    
    # Use scipy.stats.ttest_ind_from_stats.
    t2, p2 = ttest_ind_from_stats(abar, np.sqrt(avar), na,
                                  bbar, np.sqrt(bvar), nb,
                                  equal_var=False)
    print("ttest_ind_from_stats: t = %g  p = %g" % (t2, p2))
    
    # Use the formulas directly.
    tf = (abar - bbar) / np.sqrt(avar/na + bvar/nb)
    dof = (avar/na + bvar/nb)**2 / (avar**2/(na**2*adof) + bvar**2/(nb**2*bdof))
    pf = 2*stdtr(dof, -np.abs(tf))
    
    print("formula:              t = %g  p = %g" % (tf, pf))
    

    输出:

    ttest_ind:            t = -1.5827  p = 0.118873
    ttest_ind_from_stats: t = -1.5827  p = 0.118873
    formula:              t = -1.5827  p = 0.118873
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看