如何遍历pandas数据帧为每个变量运行独立的ttest?

问题描述

我有一个包含大约 33 个变量的数据集。数据集包含患者信息,感兴趣的结果本质上是二进制的。以下是部分数据。

数据集存储为熊猫数据框

df.head()
ID     Age  GAD  PHQ  Outcome
1      23   17   23      1
2      54   19   21      1
3      61   23   19      0
4      63   16   13      1
5      37   14   8       0

我想运行独立的 t 检验,以查看基于结果的患者信息差异。因此,如果我要对每个人单独进行 t 检验,我会这样做:

age_neg_outcome = df.loc[df.outcome ==0,['Age']]
age_pos_outcome = df.loc[df.outcome ==1,['Age']]

t_age,p_age = stats.ttest_ind(age_neg_outcome,age_pos_outcome,unequal = True)

print('\t Age: t= ',t_age,'with p-value= ',p_age)

如何在 for 循环中为每个变量执行此操作?

我看过这个帖子,它有点相似,但无法使用。

Python : T test ind looping over columns of df

解决方法

你快到了。 ttest_ind 也接受多维数组:

cols = ['Age','GAD','PHQ']
cond = df['outcome'] == 0

neg_outcome = df.loc[cond,cols]
pos_outcome = df.loc[~cond,cols]

# The unequal parameter is invalid so I'm leaving it out
t,p = stats.ttest_ind(neg_outcome,pos_outcome)
for i,col in enumerate(cols):
    print(f'\t{col}: t = {t[i]:.5f},with p-value = {p[i]:.5f}')

输出:

    Age: t = 0.12950,with p-value = 0.90515
    GAD: t = 0.32937,with p-value = 0.76353
    PHQ: t = -0.96683,with p-value = 0.40495