You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何生成符合Fisher's exact检验要求格式的列联表

Fisher精确检验列联表格式转换方案

核心解决思路

statsmodels生成的Table对象内置了原始计数属性,直接调用属性转换即可,无需手动处理输出文本。

完整实现代码

import statsmodels.api as sm
import pandas as pd
from scipy import stats

# 示例数据构造
d = {'Gender': [1,1,0,1,0], 'Employed': [1,0,0,1,1]}
df = pd.DataFrame(d)

# 生成statsmodels列联表对象
table = sm.stats.Table.from_data(df)

# 一键转换为scipy fisher_exact要求的输入格式
contingency_table = table.table.astype(int).tolist()

# 执行Fisher精确检验
odds_ratio, p_value = stats.fisher_exact(contingency_table)

代码说明

  • table.table:statsmodels Table类的内置属性,直接返回存储列联表计数的numpy数组,对应你输出里的[[1. 1.] [1. 2.]]内容
  • astype(int):将默认的float类型计数转为整数,匹配检验函数的通用输入要求
  • tolist():将numpy数组转为Python原生嵌套列表,转换后的contingency_table打印结果为[[1, 1], [1, 2]],完全符合输入要求

注:你示例中写的stats.fisher_Exact[[1,1],[1,2]]属于笔误,scipy中Fisher精确检验的调用方式为函数调用stats.fisher_exact(列联表变量),无需用方括号直接取值。

内容的提问来源于stack exchange,提问作者Niam45

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 12:15:04