使用一个 DataFrame 中的列作为 MultiIndex 以在另一个 DataFrame 中进行 t 检验

Use columns from one DataFrame as MultiIndex for t-test in another

使用 Pandas 到 运行 t 检验将一个 DataFrame 中的列用作另一个 MultiIndexed DataFrame 的索引的最佳实践是什么?

我已经看到其他几个涉及循环的类似问题,它们似乎不太理想。

例如,我想 运行 对以下 inds 中指定的组与 dat 中不在 inds 中的组进行 t 检验数据框。

import numpy as np
import pandas as pd
from scipy.stats import ttest_ind

np.random.seed(999)
dat = pd.DataFrame(data={"Group1" : np.random.randint(1, 3, 100),
                         "Group2" : np.random.randint(1, 5, 100),
                         "Value" : np.random.normal(size=100)})
dat.set_index(["Group1", "Group2"], inplace=True)

# How to use this as indices into MultiIndex of dat for t-test?
inds = pd.DataFrame(data={"Group1" : np.random.randint(1, 4, 20),
                          "Group2" : np.random.randint(2, 6, 20)})

# My attempt using joins, seems quite innefficient
inds["ind"] = True
inds.set_index(["Group1", "Group2"], inplace=True)

df = pd.merge(dat, inds, how='outer', left_index=True, right_index=True)
df['ind'].fillna(False, inplace=True)

# run test
tst = ttest_ind(df.loc[df['ind'], 'Value'],
                df.loc[~df['ind'], 'Value'], equal_var=False, nan_policy='omit')

如何搜索 index 以获得每个子集以进行 t 检验?这样效率可能会稍微高一些。

import numpy as np
import pandas as pd
from scipy.stats import ttest_ind

np.random.seed(999)
dat = pd.DataFrame(data={"Group1" : np.random.randint(1, 3, 100),
                         "Group2" : np.random.randint(1, 5, 100),
                         "Value" : np.random.normal(size=100)})
dat.set_index(["Group1", "Group2"], inplace=True)

# How to use this as indices into MultiIndex of dat for t-test?
inds = pd.DataFrame(data={"Group1" : np.random.randint(1, 4, 20),
                          "Group2" : np.random.randint(2, 6, 20)})

# Up to here the code is the same as yours (without inds["ind"] = True)
inds.set_index(["Group1", "Group2"], inplace=True)

# Only here is different (run test)
tst = ttest_ind(dat.loc[dat.index.isin(inds.index), 'Value'],
                dat.loc[~dat.index.isin(inds.index), 'Value'], equal_var=False, nan_policy='omit')

附带说明一下,如果我正确理解您的意图,您希望使用总共 100 个样本进行 t 检验。为了在您的原始代码中实现此目的,需要使用 df.drop_duplicates().

删除因 "outer" merge 而导致的重复条目

希望对您有所帮助。