Python: Practical Introduction to Statistical Inference (t-tests, ANOVA, Chi-Square)

Python: Practical Introduction to Statistical InferenceImage by Editor
 

Statistical inference helps us study a small set of data and make conclusions about the larger group it represents. While descriptive statistics summarize information, inference methods help test hypotheses and evaluate the significance of observed patterns. With the rise of data-driven decision-making, Python has become a popular tool for statistical inference, thanks to libraries like SciPy, statsmodels, and pandas. Using Python, analysts can apply statistical tests within broader workflows involving data preparation, visualization, and machine learning.

In this article, we will explore how to perform t-tests, ANOVA, and Chi-Square tests in Python with practical examples and interpretations.

Understanding Statistical Inference

Statistical inference is the process of using data from a sample to make generalizations about a larger population. It relies on probability theory to determine how likely it is that observed patterns are due to random chance. The two main pillars of inference are estimation and hypothesis testing (such as t-tests, ANOVA, and Chi-Square).

  • Estimation: Using sample data to calculate values (like confidence intervals) that approximate population parameters.
  • Hypothesis Testing: Evaluating assumptions about a population by comparing sample data against a null hypothesis.

t-Tests

The t-test is one of the most widely used statistical tools for comparing means. It is useful when working with small samples and normally distributed data.

One-Sample t-Test

A one-sample t-test is used to determine whether the mean of a single group is significantly different from a known or hypothesized population mean.

 
import numpy as np
from scipy import stats

data = np.random.normal(100, 15, 30)  # sample data
t_stat, p_val = stats.ttest_1samp(data, popmean=100)
print("One-sample t-test: t =", t_stat, "p =", p_val)

stats.ttest_1samp() determines whether the mean of a single sample is significantly different from a specified population mean.

 
One-sample t-test: t = -0.7906783066230668 p = 0.435550523488652

The t-value (-0.79) is the test statistic, and the p-value (0.44) is greater than 0.05, so we fail to reject the null hypothesis, meaning the sample mean is not significantly different from the population mean of 100.

Independent (Two-Sample) t-Test

An independent (two-sample) t-test is used to compare the means of two independent groups to see if there is a statistically significant difference between them.

 
import numpy as np
from scipy import stats

group1 = np.random.normal(50, 10, 30)
group2 = np.random.normal(55, 10, 30)

t_stat, p_val = stats.ttest_ind(group1, group2, equal_var=False)  # Welch’s test
print("Independent t-test: t =", t_stat, "p =", p_val)

stats.ttest_ind() checks if the means of two independent groups are significantly different from each other.

 
Independent t-test: t = -0.37294091692171666 p = 0.7106280129554898

The t-value (-0.37) and the p-value (0.71) show no significant difference between the means of group1 and group2.

Paired t-Test

A paired (dependent) t-test is used to compare the means of the same group measured at two different times or under two different conditions.

 
import numpy as np
from scipy import stats

before = np.random.normal(70, 8, 20)
after = before - np.random.normal(5, 3, 20)

t_stat, p_val = stats.ttest_rel(before, after)
print("Paired t-test: t =", t_stat, "p =", p_val)

stats.ttest_rel() tests whether there is a significant difference between two related measurements, such as before-and-after values from the same group.

 
Paired t-test: t = 7.296675667991352 p = 6.392769130943338e-07

The large positive t-value (7.30) and the very small p-value (< 0.000001) indicate a strong and statistically significant difference between the “before” and “after” measurements.

ANOVA (Analysis of Variance)

While the t-test is limited to comparing two groups, ANOVA (Analysis of Variance) extends this to three or more groups.

One-Way ANOVA

A one-way ANOVA is a statistical test used to check if there are significant differences between the means of three or more independent groups based on a single factor.

 
import numpy as np
from scipy import stats

groupA = np.random.normal(10, 2, 30)
groupB = np.random.normal(12, 2, 30)
groupC = np.random.normal(14, 2, 30)

F_stat, p_val = stats.f_oneway(groupA, groupB, groupC)
print("F-statistic =", F_stat, "p-value =", p_val)

stats.f_oneway() is used to perform a one-way ANOVA test, which checks if the means of three or more independent groups are significantly different from each other.

 
F-statistic = 24.274888631118966 p-value = 4.195554132371334e-09

The F-statistic (24.27) and the extremely small p-value (< 0.00000001) suggest that there is a significant difference among the means of the three groups (A, B, C).

If ANOVA is significant, we need post-hoc tests to identify where the differences lie:

import numpy as np
from scipy import stats
from statsmodels.stats.multicomp import pairwise_tukeyhsd

# Combine data into one array
data = np.concatenate([groupA, groupB, groupC])
groups = (["A"] * len(groupA)) + (["B"] * len(groupB)) + (["C"] * len(groupC))

tukey = pairwise_tukeyhsd(endog=data, groups=groups, alpha=0.05)
print(tukey)

pairwise_tukeyhsd() identifies which specific group pairs differ after a significant ANOVA result.

 
Multiple Comparison of Means - Tukey HSD, FWER=0.05
==================================================
group1 group2 meandiff p-adj  lower  upper  reject
--------------------------------------------------
     A      B   1.9038 0.0031 0.5599 3.2477   True
     A      C   3.9265    0.0 2.5826 5.2704   True
     B      C   2.0226 0.0016 0.6787 3.3665   True

The table shows pairwise group comparisons: all pairs (A vs B, A vs C, and B vs C) have reject = True, meaning all group means differ significantly from each other.

Two-Way ANOVA

Sometimes outcomes depend on two factors. Two-way ANOVA evaluates both main effects and their interaction.

 
import numpy as np
import pandas as pd
import statsmodels.api as sm
from statsmodels.formula.api import ols

# Example dataset
np.random.seed(42)
df = pd.DataFrame({
    "score": np.random.normal(50, 10, 60),
    "method": np.repeat(["A", "B"], 30),
    "gender": np.tile(["Male", "Female", "Male"], 20)
})

model = ols("score ~ C(method) * C(gender)", data=df).fit()
anova_table = sm.stats.anova_lm(model, typ=2)
print(anova_table)
 
                          sum_sq    df         F    PR(>F)
C(method)               6.730370   1.0  0.079768  0.778653
C(gender)              37.011349   1.0  0.438656  0.510488
C(method):C(gender)   101.216010   1.0  1.199606  0.278089
Residual             4724.964970  56.0       NaN       NaN

None of the factors (method, gender) or their interaction shows significant effects, since all p-values are greater than 0.05.

Chi-Square Test

The Chi-Square test is a non-parametric test used for categorical data. It checks whether the observed frequencies differ significantly from expected frequencies.

Test of Independence

A test of independence is used to determine whether two categorical variables are statistically associated or independent of each other.

 
import numpy as np
from scipy import stats

# Rows = Gender (Male/Female), Columns = Preference (Yes/No)
table = np.array([[30, 10],
                  [20, 25]])

chi2, p, dof, expected = stats.chi2_contingency(table)
print("Chi2 =", chi2, "p-value =", p)

stats.chi2_contingency() determines whether two categorical variables are independent or statistically associated.

 
Chi2 = 6.949930555555551 p-value = 0.00838224869725173

The Chi-square statistic (6.95) with a p-value of 0.008 indicates a significant association between the two categorical variables.

Goodness-of-Fit

A goodness-of-fit test is used to determine whether the observed frequency distribution of a categorical variable matches an expected theoretical distribution.

 
import numpy as np
from scipy import stats

observed = np.array([50, 30, 20])
expected_proportions = np.array([0.5, 0.3, 0.2])
expected = expected_proportions * observed.sum()

chi2, p_val = stats.chisquare(f_obs=observed, f_exp=expected)
print("Chi2 =", chi2, "p-value =", p_val)

stats.chisquare() tests whether the observed frequency distribution matches an expected theoretical distribution.

 
Chi2 = 0.0 p-value = 1.0

The Chi-square statistic (0.0) and the p-value (1.0) show that the observed frequencies exactly match the expected proportions, so there is no significant difference.

Practical Considerations

When applying statistical inference, it’s important to keep these in mind:

  • Normality: Parametric tests like t-tests and ANOVA assume normally distributed data. This can be checked with scipy.stats.shapiro() or visual methods such as histograms and Q-Q plots.
  • Sample size: Small samples reduce statistical power and increase the risk of missing real effects (Type II errors). Larger samples generally provide more stable estimates.
  • Multiple comparisons: Running many tests raises the risk of false positives. Techniques such as Bonferroni correction or post-hoc tests help control this issue.
  • Effect size: A statistically significant result may not always be practically important. Reporting measures like Cohen’s d (for t-tests) or eta-squared (for ANOVA) provides additional context.

Conclusion

Statistical inference is essential for validating insights and guiding data-driven decisions. t-tests, ANOVA, and Chi-Square provide versatile tools to analyze both numerical and categorical data. With Python’s libraries, these methods become easy to apply and interpret. Hands-on practice bridges the gap between statistical theory and real-world application. By mastering these tests, learners strengthen both their analytical and coding skills.

4 Replies to “Python: Practical Introduction to Statistical Inference (t-tests, ANOVA, Chi-Square)”

  1. I am a 87 year old retired economist who has, in the past relied upon charting. If I were to send you data, what you expect to be paid for correlation calculations and inference calculations , if you think they are appropriate?

    1. Hi Erik…While we do not offer such services, we are always willing to answer any questions regarding our content.

  2. I’m undertaking a stats degree with the OU in the UK, and I found this summary very helpful. From the course I know how to code these tests in R but it’s good to see how they translate to Python too. Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *