gpt4 book ai didi

Python、Pandas 和卡方独立性检验

转载 作者:太空狗 更新时间:2023-10-30 00:43:01 27 4
gpt4 key购买 nike

我对 Python 和统计学都很陌生。我正在尝试应用卡方检验来确定以前的成功是否会影响一个人的变化水平(百分比方面,情况似乎确实如此,但我想看看我的结果是否具有统计意义)。

我的问题是:我这样做是否正确?我的结果表明 p 值为 0.0,这意味着我的变量之间存在显着关系(这当然是我想要的......但是 0 对于 p 值来说似乎有点太完美了,所以我想知道我是否在编码方面做得不正确)。

这是我做的:

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

d = {'Previously Successful' : pd.Series([129.3, 182.7, 312], index=['Yes - changed strategy', 'No', 'col_totals']),
'Previously Unsuccessful' : pd.Series([260.17, 711.83, 972], index=['Yes - changed strategy', 'No', 'col_totals']),
'row_totals' : pd.Series([(129.3+260.17), (182.7+711.83), (312+972)], index=['Yes - changed strategy', 'No', 'col_totals'])}

total_summarized = pd.DataFrame(d)

observed = total_summarized.ix[0:2,0:2]

输出: Observed

expected =  np.outer(total_summarized["row_totals"][0:2],
total_summarized.ix["col_totals"][0:2])/1000

expected = pd.DataFrame(expected)

expected.columns = ["Previously Successful","Previously Unsuccessful"]
expected.index = ["Yes - changed strategy","No"]

chi_squared_stat = (((observed-expected)**2)/expected).sum().sum()

print(chi_squared_stat)

crit = stats.chi2.ppf(q = 0.95, # Find the critical value for 95% confidence*
df = 8) # *

print("Critical value")
print(crit)

p_value = 1 - stats.chi2.cdf(x=chi_squared_stat, # Find the p-value
df=8)
print("P value")
print(p_value)

stats.chi2_contingency(observed= observed)

输出 Statistics

最佳答案

一些更正:

  • 您的预期 数组不正确。您必须除以 observed.sum().sum(),即 1284,而不是 1000。
  • 对于像这样的 2x2 列联表,自由度是 1,而不是 8。
  • 您的 chi_squared_stat 计算不包括 continuity correction . (但不使用它并不一定是错误的——这是对统计学家的判断。)

您执行的所有计算(预期矩阵、统计数据、自由度、p 值)均由 chi2_contingency 计算得出:

In [65]: observed
Out[65]:
Previously Successful Previously Unsuccessful
Yes - changed strategy 129.3 260.17
No 182.7 711.83

In [66]: from scipy.stats import chi2_contingency

In [67]: chi2, p, dof, expected = chi2_contingency(observed)

In [68]: chi2
Out[68]: 23.383138325890453

In [69]: p
Out[69]: 1.3273696199438626e-06

In [70]: dof
Out[70]: 1

In [71]: expected
Out[71]:
array([[ 94.63757009, 294.83242991],
[ 217.36242991, 677.16757009]])

默认情况下,chi2_contingency 在列联表为 2x2 时使用连续性校正。如果您不想使用更正,可以使用参数 correction=False 禁用它:

In [73]: chi2, p, dof, expected = chi2_contingency(observed, correction=False)

In [74]: chi2
Out[74]: 24.072616672232893

In [75]: p
Out[75]: 9.2770200776879643e-07

关于Python、Pandas 和卡方独立性检验,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43963606/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com