【问题标题】:How to perform t-test between two groups in pandas如何在熊猫的两组之间进行t检验
【发布时间】:2019-03-04 09:38:17
【问题描述】:

我的数据框如下所示:

exp    itr    res1
e01     1      20
e01     2      21 
e01     3      22
e01     4      23

e01     5      24
e01     6      25
e01     7      26
e01     8      27

e02     .       .
e02     .       .

我必须根据 itr 将数据分成两组,即一组中的 itr 1-4 和其他组中的 itr 5-8

然后我必须计算这两组的t检验:

我当前的代码是:

 data_top4=data.groupby('exp').head(4)
 data_bottom4=data.groupby('exp').tail(4)

  tt_df.groupby('exp').apply(lambda df: 
  stats.ttest_ind(data.groupby('exp').head(4), data.groupby('exp').tail(4) 
  [0])

它无法正常运行并出现错误!

【问题讨论】:

    标签: pandas merge pandas-groupby t-test


    【解决方案1】:

    您可以使用自定义函数:

    from scipy.stats import ttest_ind
    
    def f(x):
    
        cat1_1 = x.head(4)
        cat1_2 = x.tail(4)
    
        t, p = ttest_ind(cat1_1['res1'], cat1_2['res1'])
        return pd.Series({'t':t, 'p':p})     
    
    out = data.groupby('exp').apply(f) 
    print (out)
               t         p
    exp                   
    e01 -4.38178  0.004659
    

    编辑:

    def f(x):
    
        cat1_1 = x.head(4)
        cat1_2 = x.tail(4)
    
        t, p = ttest_ind(cat1_1, cat1_2)
        return pd.Series({'t':t, 'p':p})     
    
    out = data.groupby('exp')['res1'].apply(f).unstack()
    print (out)
               t         p
    exp                   
    e01 -4.38178  0.004659
    

    或者:

    def f(x, col):
    
        cat1_1 = x.head(4)
        cat1_2 = x.tail(4)
    
        t, p = ttest_ind(cat1_1[col], cat1_2[col])
        return pd.Series({'t':t, 'p':p})     
    
    out = data.groupby('exp').apply(f, 'res1') 
    print (out)
               t         p
    exp                   
    e01 -4.38178  0.004659
    

    【讨论】:

    • 如果我需要再向函数传递 1 个参数,我需要做什么。我需要将 ['res1'] 作为参数传递给函数
    • @tejasshah - 检查已编辑的答案 - 可以在第二个解决方案中的 groupby 之后定义列名称以进行检查,或者像上一个一样在 apply 中传递值。
    猜你喜欢
    • 2017-12-14
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多