将一个数据帧中的列用作另一个数据帧中的 t 检验的多索引



使用 Pandas 将一个数据帧中的列用作另一个多索引数据帧的索引来运行 t 检验的最佳实践是什么?

我看到过其他几个类似的问题,这些问题涉及在这里循环,似乎并不理想。

例如,我想对以下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()删除由于"外部"merge而导致的重复条目。

希望这有帮助。

最新更新