简体   繁体   English

如何循环通过 pandas dataframe 为每个变量运行独立的测试?

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

I have a dataset that consists of around 33 variables.我有一个包含大约 33 个变量的数据集。 The dataset contains patient information and the outcome of interest is binary in nature.数据集包含患者信息,感兴趣的结果本质上是二进制的。 Below is a snippet of the data.下面是数据片段。

The dataset is stored as a pandas dataframe数据集存储为 pandas dataframe

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

I want to run independent t-tests looking at the differences in patient information based on outcome.我想运行独立的 t 检验,根据结果查看患者信息的差异。 So, if I were to run a t-test for each alone, I would do:所以,如果我要单独对每个人进行 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)

How can I do this in a for loop for each of the variables?如何在每个变量的 for 循环中执行此操作?

I've seen this post which is slightly similar but couldn't manage to use it.我看过这篇文章,有点相似,但无法使用它。

Python: T test ind looping over columns of df Python:T 测试 ind 在 df 列上循环

You are almost there.你快到了。 ttest_ind accepts multi-dimensional arrays too: ttest_ind接受多维 arrays :

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}')

Output: Output:

    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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM