[英]T-Test in Python for multiple group comparisons
I would like to conduct a simple t-test in python, but I would like to compare all possible groups to each other.我想在 python 中进行一个简单的 t 检验,但我想将所有可能的组相互比较。 Let's say I have the following data:
假设我有以下数据:
import pandas as pd
data = {'Category': ['cat3','cat2','cat1','cat2','cat1','cat2','cat1','cat2','cat1','cat1','cat1','cat2','cat3','cat3'],
'values': [4,1,2,3,1,2,3,1,2,3,5,1,6,3]}
my_data = pd.DataFrame(data)
And I want to calculate the p-value based on a t-test for all possible category combinations, which are:我想根据所有可能的类别组合的 t 检验计算 p 值,它们是:
cat1 vs. cat2
cat2 vs. cat3
cat1 vs. cat3
I can do this manually via:我可以通过以下方式手动执行此操作:
from scipy import stats
cat1 = my_data.loc[my_data['Category'] == 'cat1', 'values']
cat2 = my_data.loc[my_data['Category'] == 'cat2', 'values']
cat3 = my_data.loc[my_data['Category'] == 'cat3', 'values']
print(stats.ttest_ind(cat1,cat2).pvalue)
print(stats.ttest_ind(cat2,cat3).pvalue)
print(stats.ttest_ind(cat1,cat3).pvalue)
But is there a more simple and straightforward way to do this?但是有没有更简单直接的方法来做到这一点? The amount of categories might differ from case to case, so the number of t-tests that need to be calculated will also differ...
类别的数量可能因情况而异,因此需要计算的 t 检验数量也会有所不同......
The final output should be a DataFrame with one row for each comparison and the values: category1 |最终输出应该是一个 DataFrame,每个比较和值占一行: category1 | category2 |
类别2 | p-value, in this case it should look like:
p 值,在这种情况下它应该如下所示:
cat1 | cat2 | 0.16970867501294376
cat2 | cat3 | 0.0170622126550303
cat1 | cat3 | 0.13951958313684434
Consider iterating through itertools.combinations
across categories:考虑跨类别迭代
itertools.combinations
:
from itertools import combinations
...
def ttest_run(c1, c2):
results = stats.ttest_ind(cat1, cat2)
df = pd.DataFrame({'categ1': c1,
'categ2': c2,
'tstat': results.statistic,
'pvalue': results.pvalue},
index = [0])
return df
df_list = [ttest_run(i, j) for i, j in combinations(mydata['Category'].unique().tolist(), 2)]
final_df = pd.concat(df_list, ignore_index = True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.