如何在 pandas 中的两组之间进行 t 检验

How to perform t-test between two groups in pandas

我的数据框如下所示:

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])

它不能正常运行并且有错误!

您可以使用自定义函数:

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