1

如果这个问题很幼稚,请提前道歉。我是 Python 新手。我正在尝试对我的数据框的两列执行 t 检验。只有在将列按同一数据框中的另一列分组后进行 t 检验才有意义。

我正在处理这样的事情:

rand_array = np.random.randint(low=10, high=30, size=9)
rand_array2 = np.random.randint(low=10, high=30, size=9)
d = {'key1':[0,0,1,0,1,1,1,0,1], 'key2': rand_array, 'key3': rand_array2}
df1 = pd.DataFrame(d)
print df1

我得到的输出是:

     key1  key2  key3
0     0    20    18
1     0    22    16
2     1    21    26
3     0    21    13
4     1    11    21
5     1    23    10
6     1    17    29
7     0    13    25
8     1    24    29

然后,我按 key1 分组

g1 = df1.groupby('key1')
print g1.groups
>>> {0: Int64Index([0, 1, 3, 7], dtype='int64'), 1: Int64Index([2, 4, 5, 6, 8], dtype='int64')}

我想对基本上 0: Int64Index([0, 1, 3, 7], dtype='int64') vs 1: Int64Index([2, 4, 5, 6, 8], dtype=' int64')。

这可能吗?

谢谢!

4

1 回答 1

2

参见Welch 的 T 检验

我会这样做:

def welch_ttest(x1, x2):
    x_1 = x1.mean()
    x_2 = x2.mean()
    s1 = x1.std()
    s2 = x2.std()
    n1 = len(x1)
    n2 = len(x2)
    return ((x_1 - x_2) / (np.sqrt(s1 ** 2 / n1 + s2 ** 2 / n2)))

def grouped_welch_ttest(df):
    return welch_ttest(df.key2, df.key3)

df1.groupby('key1').apply(grouped_welch_ttest)

key1
0   -1.471497
1    1.487045
dtype: float64
于 2017-02-18T14:41:33.970 回答