🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Data Science & Analytics › Statistics for Data Science & Analytics › Lesson 7
TEC-DATA85-02 · Lesson 7 · 12 clock hours · lab

Two-Sample Tests and Chi-Square Analysis

Objective. Students apply independent two-sample t-tests and chi-square tests of independence to answer business and policy questions from tabular data.

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

Two-Sample Tests and Chi-Square Analysis

When you need to compare two groups or test whether two categorical variables are related, two workhorses of inferential statistics cover most situations: the independent two-sample t-test and the chi-square test of independence. Both appear regularly in business dashboards, policy reports, and data science projects — and both are tested on CompTIA Data+, the Google Data Analytics certificate, and IBM Data Science Professional assessments.

The Independent Two-Sample t-Test

The independent two-sample t-test asks: do two separate groups have the same population mean? For example, does City Department A resolve service requests in the same average time as City Department B?

Hypotheses

You choose a significance level — commonly α = 0.05 — before running the test. If the p-value returned by the test is less than α, you reject H₀.

Assumptions You Must Check

1. Independence: Observations in each group must not influence the other group. Department A's response times should not overlap with Department B's records.

2. Approximate normality: Each group's data should be roughly normally distributed, or the sample sizes should be large enough (often cited as n ≥ 30 per group) for the Central Limit Theorem to apply. A histogram or Q-Q plot helps you check this visually.

3. Equal (or unequal) variances: `scipy.stats.levene()` performs Levene's test. If Levene's p-value is below α, the variances differ significantly and you should pass `equal_var=False` to `scipy.stats.ttest_ind()`, which uses Welch's t-test instead of Student's t-test. Welch's version is generally safer and is the recommended default.

Running the Test in Python

```python

from scipy import stats

t_stat, p_value = stats.ttest_ind(dept_a, dept_b, equal_var=False)

print(f"t = {t_stat:.3f}, p = {p_value:.4f}")

```

If `p_value < 0.05`, you reject H₀ and conclude the mean response times differ. Always report the direction of the difference (which group was faster) and the practical size of that difference, not just the p-value.

The Chi-Square Test of Independence

The chi-square test of independence asks: are two categorical variables associated, or are they independent? For example, does the type of customer complaint (billing, delivery, product quality) depend on the customer's region?

The Contingency Table

You arrange counts in a contingency table with rows representing one variable and columns representing the other. Each cell holds the observed count for that combination.

Expected Frequencies

Under H₀ (the variables are independent), the expected count for a cell is:

> Expected = (Row Total × Column Total) / Grand Total

This formula embodies the assumption that if the variables are truly independent, each cell should hold exactly the proportion you would predict from the marginals alone. You must verify that no expected cell count falls below 5 — a key assumption of the chi-square approximation. If cells are too sparse, combine categories or use Fisher's exact test.

Computing the Chi-Square Statistic

The chi-square statistic sums the standardized squared deviations between observed (O) and expected (E) counts across all cells:

> χ² = Σ [(O − E)² / E]

A larger χ² means the observed data deviate more from what independence predicts.

Running the Test in Python

```python

from scipy.stats import chi2_contingency

import numpy as np

table = np.array([[34, 20, 15],

[18, 42, 10],

[12, 25, 30]])

chi2, p, dof, expected = chi2_contingency(table)

print(f"χ² = {chi2:.3f}, p = {p:.4f}, df = {dof}")

print("Expected:\n", expected)

```

If `p < 0.05`, you reject H₀ and conclude the two variables are associated.

Writing the Interpretation

A correct written interpretation has four parts:

1. State the test used and the α level chosen.

2. Report the test statistic and p-value.

3. State the decision (reject or fail to reject H₀).

4. Give a plain-language conclusion that answers the original business question.

Example: "Using an independent two-sample t-test at α = 0.05, we found t = −3.12, p = 0.002. We reject H₀ and conclude that Department A resolves requests significantly faster than Department B on average."

Data Accuracy and Integrity

Before running any test, verify your dataset for duplicate rows, missing values, and data-entry errors. A test run on dirty data produces misleading results that can misinform policy decisions — a real professional and ethical concern. Document every cleaning step in your notebook so the analysis is reproducible.

Lab Safety Note

This is a software lab. Follow your program's acceptable-use policy for shared computing resources. Do not upload identifiable personal data to public notebooks or cloud services without verifying that privacy requirements are met. Handle open datasets responsibly and cite your sources.

Key terms10

Independent two-sample t-testA hypothesis test that compares the means of two separate, unrelated groups to determine whether they differ significantly.
Null hypothesis (H₀)The default assumption that there is no effect or no difference between groups; the test attempts to find evidence against it.
Significance level (α)The probability threshold — commonly 0.05 — below which the p-value must fall for the analyst to reject the null hypothesis.
Levene's testA preliminary test that checks whether two or more groups have equal variances; a significant result means variances differ and Welch's t-test should be used.
Welch's t-testA variant of the two-sample t-test that does not assume equal variances between groups; recommended as the default in most practical situations.
Contingency tableA grid that displays the observed frequency counts for every combination of two categorical variables.
Expected frequencyThe cell count predicted under the assumption of independence, calculated as (row total × column total) / grand total.
Chi-square statistic (χ²)A measure of how much the observed cell counts deviate from expected counts under independence; larger values indicate greater association.
Degrees of freedom (df)For a chi-square test of independence, df = (number of rows − 1) × (number of columns − 1); it determines which chi-square distribution is used to find the p-value.
p-valueThe probability of observing a test statistic at least as extreme as the one calculated, assuming the null hypothesis is true; a small p-value is evidence against H₀.

Worked examples4

1. A city analyst records mean response times (in hours) for two departments. Department A: n = 40, mean = 18.4 h, SD = 4.2 h. Department B: n = 35, mean = 21.1 h, SD = 5.8 h. Levene's test returns p = 0.08. Using α = 0.05, should the analyst use Student's or Welch's t-test, and what is the conclusion if the test returns p = 0.009?
  1. Step 1 — Check Levene's result: p = 0.08 > 0.05, so we fail to reject equal variances. However, since the SDs differ notably (4.2 vs. 5.8) and Welch's is safer by convention, many analysts use equal_var=False regardless. Either choice is defensible; document it.
  2. Step 2 — State hypotheses: H₀: μ_A = μ_B; H₁: μ_A ≠ μ_B (two-tailed). α = 0.05.
  3. Step 3 — Run ttest_ind with equal_var=False (Welch's). The test returns p = 0.009.
  4. Step 4 — Decision: p = 0.009 < α = 0.05, so reject H₀.
  5. Step 5 — Interpret: Department A's mean response time (18.4 h) is significantly lower than Department B's (21.1 h) at the 0.05 level. The difference is approximately 2.7 hours.
Answer: Use Welch's t-test (equal_var=False). Because p = 0.009 < 0.05, reject H₀. Department A resolves requests significantly faster than Department B, with a mean difference of about 2.7 hours.
2. A contingency table shows complaint type by region for 120 customers. Billing: North = 30, South = 20 (row total = 50). Delivery: North = 18, South = 12 (row total = 30). Product quality: North = 12, South = 28 (row total = 40). Column totals: North = 60, South = 60. Grand total = 120. Calculate the expected frequency for the Billing/North cell.
  1. Step 1 — Identify the row total for Billing: 30 + 20 = 50.
  2. Step 2 — Identify the column total for North: 30 + 18 + 12 = 60.
  3. Step 3 — Identify the grand total: 120.
  4. Step 4 — Apply the formula: Expected = (Row Total × Column Total) / Grand Total = (50 × 60) / 120 = 3000 / 120 = 25.
Answer: The expected frequency for the Billing/North cell is 25.
3. Using the same contingency table from the previous example, calculate the chi-square contribution for just the Billing/North cell (Observed = 30, Expected = 25) and the Billing/South cell (Observed = 20, Expected = 25). What is the combined contribution of the Billing row to χ²?
  1. Step 1 — Billing/North contribution: (O − E)² / E = (30 − 25)² / 25 = 25 / 25 = 1.00.
  2. Step 2 — Billing/South contribution: (O − E)² / E = (20 − 25)² / 25 = 25 / 25 = 1.00.
  3. Step 3 — Sum for the Billing row: 1.00 + 1.00 = 2.00.
Answer: The Billing row contributes 2.00 to the overall χ² statistic.
4. A chi-square test of independence on a 3 × 2 contingency table returns χ² = 8.45. At α = 0.05, the critical value for the appropriate degrees of freedom is approximately 5.99. State the degrees of freedom, the decision, and a one-sentence plain-language conclusion for a study of whether complaint type is associated with region.
  1. Step 1 — Degrees of freedom: df = (rows − 1) × (columns − 1) = (3 − 1) × (2 − 1) = 2 × 1 = 2.
  2. Step 2 — Compare statistic to critical value: χ² = 8.45 > 5.99 (critical value at df = 2, α = 0.05), so reject H₀.
  3. Step 3 — State the conclusion: There is a statistically significant association between complaint type and region at α = 0.05.
  4. Step 4 — Plain language: The data provide sufficient evidence that the kind of complaint a customer makes depends on which region they are in.
Answer: df = 2. Reject H₀ (8.45 > 5.99). Conclusion: Complaint type and customer region are significantly associated; the type of complaint a customer submits is not independent of their region.

The math in this lesson1

Learners run two-sample t-tests and chi-square tests to compare groups.
S-IC.5
Brush up in the math halls at newSchoolWorks.com:
In class: Two-sample t-test lab: students compare mean response times of two city departments using an open dataset; they check assumptions (normality, equal variance via Levene's test), run the test in scipy.stats, and interpret results in a short paragraph. · Chi-square activity: given a contingency table of customer complaint types by region, students compute expected frequencies by hand, verify in Python, run chi_square contingency from scipy.stats, and state whether the variables are associated. · Peer review: each student exchanges their written interpretation with a partner, checks for correct α-level reference, correct rejection decision, and plain-language conclusion; they give written feedback on one strength and one error.
Materials: Jupyter Notebook, scipy.stats (ttest_ind, levene, chi2_contingency); city department response-time CSV; contingency table handout; OpenIntro Statistics Chapter 6
Check: Instructor evaluates completed notebooks; student must correctly run both test types and write accurate interpretations; pass mark 70% on a 10-point rubric.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

Statistical analysis and hypothesis testing
1. Before running a two-sample t-test, an analyst runs Levene's test and gets p = 0.02 with α = 0.05. What should the analyst do?
Statistical analysis and hypothesis testing
2. In a two-sample t-test, the p-value is 0.13 and α = 0.05. What is the correct decision?
Data analysis tools and programming
3. Which Python function from scipy.stats is used to run a chi-square test of independence on a contingency table?
Statistical analysis and hypothesis testing
4. A contingency table has 4 rows and 3 columns. How many degrees of freedom does the chi-square test of independence have?
Statistical analysis and hypothesis testing
5. The expected frequency for one cell in a chi-square test is 3. What is the appropriate action?
Statistical analysis and hypothesis testing
6. An analyst compares customer satisfaction scores between two store locations. The data for each location are independent. Which test is most appropriate?
Statistical analysis and hypothesis testing
7. A chi-square test returns χ² = 9.21, df = 2, p = 0.01 at α = 0.05. Which conclusion is correct?
Data interpretation and communication
8. A student's written test interpretation states: 'p = 0.03, so we reject H₀ and conclude there is a significant difference.' A peer reviewer notes the interpretation is missing one critical element. What is it?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.