微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何遍历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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。