【发布时间】:2018-08-28 16:01:21
【问题描述】:
UCLA 有这个很棒的统计测试网站
但代码都在 R 中。我正在尝试将代码转换为 Python 等价物,但对于卡方拟合优度等某些人来说,这不是一个简单的过程。这是 R 版本:
hsb2 <- within(read.csv("https://stats.idre.ucla.edu/stat/data/hsb2.csv"), {
race <- as.factor(race)
schtyp <- as.factor(schtyp)
prog <- as.factor(prog)
})
chisq.test(table(hsb2$race), p = c(10, 10, 10, 70)/100)
我的 Python 尝试是这样的:
import numpy as np
import pandas as pd
from scipy import stats
df = pd.read_csv("https://stats.idre.ucla.edu/stat/data/hsb2.csv")
# convert to category
df["race"] = df["race"].astype("category")
t_race = pd.crosstab(df.race, columns = 'race')
p_tests = np.array((10, 10, 10, 70))
p_tests = ptests/100
# tried this
stats.chisquare(t_race, p_tests)
# and this
stats.chisquare(t_race.T, p_tests)
但是 stats.chisquare 的输出都没有接近 R 版本。任何人都可以引导我朝着正确的方向前进吗? TIA
【问题讨论】:
标签: python r chi-squared