【问题标题】:Group by groups to Pandas Series/Dataframe按组分组到熊猫系列/数据框
【发布时间】:2017-07-08 01:23:58
【问题描述】:

如果这个问题很幼稚,请提前道歉。我是 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') 与 1: Int64Index([2, 4, 5, 6, 8], dtype='int64')。

这可能吗?

谢谢!

【问题讨论】:

    标签: pandas group-by series t-test


    【解决方案1】:

    见Welch's T-Test

    我会这样做:

    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
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-19
    • 2022-01-12
    • 1970-01-01
    • 2020-06-03
    • 2013-02-28
    • 2019-10-14
    • 1970-01-01
    • 2016-06-04
    相关资源
    最近更新 更多