如何通过 pandas 数据帧循环到 运行 每个变量的独立 t 检验?

How to loop through a pandas dataframe to run an independent ttest for each of the variables?

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

数据集存储为 pandas 数据帧

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 循环中执行此操作?

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

你快到了。 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