from scipy.stats import chi2_contingency
# 교차표 생성
table = pd.crosstab(df['Gender'], df['Survived'])
# 검정 수행
statistics, p, df, expected = chi2_contingency(table)
# 또는 간단히
print(chi2_contingency(table))
결과 해석 팁:
from scipy.stats import ttest_1samp, ttest_ind, ttest_rel
# 단일표본 t-test
ttest_1samp()
# 독립표본 t-test
ttest_ind()
# 대응표본 t-test
ttest_rel()
from statsmodels.api import Logit, sm
from sklearn.preprocessing import LabelEncoder
# 범주형 변수 전처리
encoder = LabelEncoder()
df['Gender'] = encoder.fit_transform(df['Gender'])
# 변수 설정
X = df[['Gender', 'SibSp', 'Parch', 'Fare']]
X = sm.add_constant(X) # 절편 추가
y = df['Survived']
# 모델 학습
model = Logit(y, X)
results = model.fit()
print(results.summary())
# 더 간단하고 편리한 방법
formula = "Survived ~ Gender + SibSp + Parch + Fare"
results = Logit.from_formula(formula, df).fit()
print(results.summary())
장점:
import numpy as np
# 방법 1: 변수명으로 계산
print(np.exp(results.params['SibSp']))
# 방법 2: 계수값 직접 입력
print(round(np.exp(-0.3539), 3))
from statsmodels.api import OLS
# 로지스틱과 동일한 formula 방식 사용 가능
formula = "y ~ x1 + x2 + x3"
results = OLS.from_formula(formula, df).fit()
print(results.summary())