首页 > 解决方案 > 统计模型列联表nd数组2 x 2 xk,无法重塑

问题描述

考虑下面的 2x2 表列表和 CMH(Cochran-Mantel-Haenszel)测试结果。我们正在尝试确定每个特定中心是否与治疗成功有关[来自 Agresti 的数据,分类数据分析,第二版]

在此处输入图像描述

tables= [
[[11, 10], [25, 27]],
 [[16, 22], [4, 10]],
 [[14, 7], [5, 12]],
 [[2, 1], [14, 16]],
 [[6, 0], [11, 12]],
 [[1, 0], [10, 10]],
 [[1, 1], [4, 8]],
 [[4, 6], [2, 1]]]

cmh = sm.stats.contingency_tables.StratifiedTable(tables = tables)
print(cmh.test_null_odds())
pvalue ~ 0.012
statistic ~ 6.38

StratifiedTable中的表参数也可以采用 numpy 数组形状 2 x 2 xk,其中 k 是返回每个列联表的切片。
我一直无法围绕数组重新整形,这基于上述 8、2、2 形状的列表可以更直观地提供(至少对我而言)。

关于如何使用 nd 数组重新运行相同的测试的任何问题?

更新:我试图按照下面评论中的建议将我的表 var 在 numpy 中重塑为带有转置的 nd 数组 2 x 2 xk 。TypeError运行相同的测试时会出现 以下问题TypeError: No loop matching the specified signature and casting was found for ufunc true_divide

注意:在 R 中,以下矩阵将返回所需的输出

data = array (c(11, 10, 25, 27, 16, 22, 4, 10,
     14, 7, 5, 12, 2, 1, 14, 16,
      6, 0, 11, 12, 1, 0, 10, 10,
      1, 1, 4, 8, 4, 6, 2, 1), 
      c(2,2,8))
mantelhaen.test(data, correct=F)

标签: pythonnumpystatsmodels

解决方案


只需引用@Josef 评论作为答案。我错过/没有考虑 dtype 转换。

你的例子适用于我的转置,.T。看起来你对 dtype 有一个单独的问题。使用浮点数:tables = np.asarray(tables).T.astype(float)最近修复了 github.com/statsmodels/statsmodels/pull/7279


推荐阅读