0Pricing
Pandas & NumPy Academy · 강의

독립성에 대한 카이제곱 검정

교차표 빈도표에서 chi2_contingency를 사용해 두 범주형 변수가 독립인지 검정합니다.

독립성에 대한 카이제곱 검정은(는) CoddyKit의 무료 Pandas & NumPy Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Pandas & NumPy Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Testing Categorical Relationships

The chi-squared test for independence tests whether two categorical variables are statistically independent or whether there is an association between them. For example: 'Is customer churn independent of subscription tier?' or 'Is product preference independent of age group?' Unlike t-tests that compare numeric means, chi-squared tests compare observed frequencies in a contingency table to the frequencies we would expect if the variables were independent.

Building a Contingency Table with Pandas

A contingency table (also called a cross-tabulation) shows the count of observations for each combination of two categorical variables. pd.crosstab(df['var1'], df['var2']) builds this table directly from a DataFrame. Each cell contains the count of observations where row category and column category co-occur. This is the input to scipy.stats.chi2_contingency().

import pandas as pd
import numpy as np

np.random.seed(0)
df = pd.DataFrame({
    'subscription': np.random.choice(['free', 'basic', 'pro'], 300),
    'churned': np.random.choice(['yes', 'no'], 300, p=[0.3, 0.7])
})

# Build contingency table
ct = pd.crosstab(df['subscription'], df['churned'])
print(ct)
print()
print('Row totals:', ct.sum(axis=1).to_dict())

Running chi2_contingency()

scipy.stats.chi2_contingency(observed) takes the observed contingency table (as a NumPy array or Pandas DataFrame) and returns four values: the chi-squared statistic, the p-value, the degrees of freedom, and the expected frequency table. The null hypothesis is H₀: the two variables are independent. If p ≤ 0.05, we reject independence and conclude there is a statistically significant association.

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

np.random.seed(0)
df = pd.DataFrame({
    'tier': np.random.choice(['free', 'basic', 'pro'], 300),
    'churned': np.random.choice(['yes', 'no'], 300, p=[0.3, 0.7])
})

ct = pd.crosstab(df['tier'], df['churned'])
chi2, p, dof, expected = stats.chi2_contingency(ct)

print(f'Chi-squared: {chi2:.3f}')
print(f'p-value: {p:.4f}')
print(f'Degrees of freedom: {dof}')
print('Association significant?', 'Yes' if p < 0.05 else 'No')

Understanding Expected Frequencies

The expected frequencies represent what the cell counts would look like if the two variables were perfectly independent. For each cell, expected = (row_total × column_total) / grand_total. The chi-squared statistic measures the sum of squared differences between observed and expected counts, normalised by the expected counts. Large chi-squared means observed counts deviate strongly from independence; small chi-squared means the data is consistent with independence.

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

observed = pd.DataFrame({
    'converted': [50, 30],
    'not_converted': [150, 170]
}, index=['variant', 'control'])

chi2, p, dof, expected = stats.chi2_contingency(observed)
print('Observed:')
print(observed)
print()
print('Expected (under independence):')
print(pd.DataFrame(expected,
                   index=observed.index,
                   columns=observed.columns).round(1))

Degrees of Freedom in Chi-Squared

For a contingency table with r rows and c columns, the degrees of freedom is df = (r-1) × (c-1). A 2×2 table has df=1; a 3×4 table has df=6. The critical value of chi-squared increases with degrees of freedom: for df=1 at α=0.05, critical value ≈ 3.84; for df=6 at α=0.05, critical value ≈ 12.6. The chi2_contingency function handles this automatically, but knowing the formula helps you understand why chi-squared from larger tables requires bigger statistics to be significant.

from scipy import stats

# Critical values of chi-squared for alpha=0.05
for df in [1, 2, 3, 4, 6, 9]:
    critical = stats.chi2.ppf(0.95, df=df)
    print(f'df={df}: critical value = {critical:.3f}')

The Assumption of Minimum Expected Frequency

The chi-squared test is only reliable when all expected frequencies are at least 5 (some sources say at least 1 with no more than 20% below 5). Small expected counts make the chi-squared approximation inaccurate. When this assumption is violated, use Fisher's exact test (scipy.stats.fisher_exact()) for 2×2 tables, or collapse rare categories to increase expected counts. Always inspect the expected frequency matrix returned by chi2_contingency.

import numpy as np
from scipy import stats

# Table with small expected counts
observed = np.array([[2, 3], [100, 95]])
chi2, p, dof, expected = stats.chi2_contingency(observed)

print('Expected frequencies:')
print(expected)
print('Min expected:', expected.min())

if expected.min() < 5:
    print('Warning: Expected frequency < 5. Use Fisher\'s exact test.')
    odds_ratio, p_fisher = stats.fisher_exact(observed)
    print(f'Fisher\'s exact p: {p_fisher:.4f}')

Fisher's Exact Test for Small Samples

scipy.stats.fisher_exact(table) computes the exact probability of observing the given 2×2 table (or one more extreme) under the null hypothesis of independence, without any approximation. It is always valid regardless of sample size or cell counts — the p-value is exact, not approximate. The cost is computational: it enumerates all possible tables, making it slow for large totals. For 2×2 tables with any cell count below 5, always prefer Fisher's exact test over chi-squared.

import numpy as np
from scipy import stats

# Small clinical trial: treatment vs. outcome
observed = np.array([
    [3, 12],   # treated: 3 improved, 12 did not
    [1, 18]    # control: 1 improved, 18 did not
])

odds_ratio, p = stats.fisher_exact(observed, alternative='two-sided')
print(f'Odds ratio: {odds_ratio:.3f}')
print(f'p-value: {p:.4f}')
print('Association significant?', 'Yes' if p < 0.05 else 'No')

Measuring Association Strength: Cramér's V

Like Cohen's d for t-tests, the chi-squared statistic alone does not measure the strength of association — it is inflated by sample size. Cramér's V normalises chi-squared to a 0–1 scale: 0 means no association, 1 means perfect association. V = sqrt(chi2 / (n × min(r-1, c-1))). Guidelines: < 0.1 is weak, 0.1–0.3 is moderate, > 0.3 is strong. Always report Cramér's V alongside the p-value for a complete picture.

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

np.random.seed(0)
df = pd.DataFrame({
    'tier': np.random.choice(['free', 'basic', 'pro'], 500),
    'churn': np.random.choice(['yes', 'no'], 500, p=[0.3, 0.7])
})
ct = pd.crosstab(df['tier'], df['churn'])

chi2, p, dof, _ = stats.chi2_contingency(ct)
n = ct.sum().sum()
min_dim = min(ct.shape[0]-1, ct.shape[1]-1)
cramers_v = np.sqrt(chi2 / (n * min_dim))

print(f'chi2={chi2:.3f}, p={p:.4f}')
print(f'Cramer\'s V: {cramers_v:.4f}')
print('Association strength:', 'strong' if cramers_v > 0.3 else 'moderate' if cramers_v > 0.1 else 'weak')

Chi-Squared Goodness of Fit

A different application of chi-squared is the goodness-of-fit test: it tests whether observed frequencies match a hypothesised distribution. For example, 'Are die rolls uniformly distributed?' or 'Does our website traffic follow the expected day-of-week pattern?' Use scipy.stats.chisquare(f_obs, f_exp) where f_exp is the expected frequencies. The null hypothesis is that the data follows the specified distribution.

import numpy as np
from scipy import stats

# Observed: counts for each weekday over 70 weeks
observed = np.array([980, 1050, 1020, 1080, 1120, 850, 900])
# Expected: uniform distribution
expected = np.full(7, observed.sum() / 7)

chi2, p = stats.chisquare(f_obs=observed, f_exp=expected)
print('Observed:', observed)
print('Expected (uniform):', expected.round(0))
print(f'chi2={chi2:.3f}, p={p:.4f}')
print('Uniform?', 'Yes' if p > 0.05 else 'No - some days significantly busier')

Using pd.crosstab with normalise

When reporting chi-squared results, it helps to show proportions rather than raw counts so readers can see the relative association. pd.crosstab(var1, var2, normalize='index') shows the row proportion (what fraction of each row category falls in each column). normalize='columns' shows column proportions. Comparing these proportions visually before running the test helps you anticipate the direction of the association and interpret the result in context.

import pandas as pd
import numpy as np

np.random.seed(0)
df = pd.DataFrame({
    'tier': np.random.choice(['free', 'basic', 'pro'], 300),
    'churned': np.random.choice(['yes', 'no'], 300, p=[0.3, 0.7])
})

# Row-proportions: churn rate within each tier
prop_table = pd.crosstab(df['tier'], df['churned'], normalize='index')
print('Churn rate by tier:')
print((prop_table * 100).round(1))

Chi-Squared Test in A/B Testing

The chi-squared test is the standard test for A/B testing conversion rates. Create a 2×2 contingency table with rows = (control, variant) and columns = (converted, not converted). The chi-squared test tells you whether the conversion rate differs significantly between groups. This is equivalent to a two-proportion z-test for large samples. For small samples (any expected count < 5), use Fisher's exact test instead.

import numpy as np
from scipy import stats

# A/B test: control vs. variant, conversions vs. non-conversions
control_conv = 45
control_total = 500
variant_conv = 63
variant_total = 500

contingency = np.array([
    [control_conv, control_total - control_conv],
    [variant_conv, variant_total - variant_conv]
])

chi2, p, dof, expected = stats.chi2_contingency(contingency)
print(f'Control rate: {control_conv/control_total:.1%}')
print(f'Variant rate: {variant_conv/variant_total:.1%}')
print(f'p-value: {p:.4f}')
print('Variant significantly better?', 'Yes' if p < 0.05 else 'No')

Quick Check

Test your understanding of Data Analysis concepts from this lesson.

Lesson Recap

In this lesson you learned: pd.crosstab() + chi2_contingency() test whether two categorical variables are independent based on observed vs. expected frequencies, Fisher's exact test is the safe alternative when expected counts are below 5, and Cramér's V measures association strength independently of sample size. Next up we compare means across three or more groups with ANOVA and post-hoc tests.

자주 묻는 질문

“독립성에 대한 카이제곱 검정” 강의는 무료인가요?

네 — “독립성에 대한 카이제곱 검정” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Pandas & NumPy Academy 강의 전체를 잠금 해제할 수 있습니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“독립성에 대한 카이제곱 검정”에서 뭘 배우나요?

교차표 빈도표에서 chi2_contingency를 사용해 두 범주형 변수가 독립인지 검정합니다. 브라우저에서 직접 실행하는 실습 코드로 Pandas & NumPy Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Pandas & NumPy Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Pandas & NumPy Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“독립성에 대한 카이제곱 검정” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Pandas & NumPy Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Pandas & NumPy Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 기술 통계와 정규성 검정
  2. 평균 비교를 위한 t 검정
  3. 독립성에 대한 카이제곱 검정
  4. ANOVA와 사후 검정
← Pandas & NumPy Academy(으)로 돌아가기