Statistics for Data Science

Statistics for Data Science is essential for understanding data, evaluating uncertainty and making reliable decisions. This course moves from measurement and probability to inference, modelling, experiments and time series. Each topic includes a formula or rule, symbol meanings, an intuitive example, Python code, interpretation, assumptions, a common mistake and a practical prompt with its solution direction. Examples use Python 3.11+ with NumPy, SciPy, statsmodels, pandas and Matplotlib where appropriate.

How to Study Statistics for Data Science Effectively

Statistics is a reasoning discipline. Begin with the data-generating process, identify the unit of analysis, inspect missingness and distribution, choose an estimand, state assumptions, calculate an estimate or test, quantify uncertainty, and communicate practical meaning. A formula is not a substitute for design: a precise estimate from a biased sample can still be wrong.

  1. Describe: use plots and robust summaries before modelling.
  2. Model uncertainty: connect samples to populations through probability and sampling distributions.
  3. Decide: separate statistical evidence from causal and business claims.
  4. Validate: check assumptions, sensitivity, residuals and out-of-sample behaviour.

Part A: foundations

A strong understanding of Statistics for Data Science helps students distinguish between population parameters, sample statistics and estimates drawn from observed data.

Topics 1–9 establish what was measured, for whom and how. Symbols: n is sample size, N population size, xᵢ an observation, x̄ sample mean, μ population mean, s sample standard deviation and σ population standard deviation.

1. What is statistics?

Concept and intuition: Statistics is the discipline of collecting, describing, modelling and communicating uncertainty in data.

Formula or rule: Statistics is the discipline of collecting, describing, modelling and communicating uncertainty in data. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: A mean of 72 from 100 exam scores describes the observed group; it does not automatically describe every student.

import numpy as npnscores = np.array([60, 70, 80])nprint(scores.mean())

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Define the population and the question before calculating a number.

2. Population and sample

Concept and intuition: A population is the complete group of interest; a sample is the observed subset used to learn about it.

Formula or rule: A population is the complete group of interest; a sample is the observed subset used to learn about it. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: If all 10,000 users are the population and 500 randomly selected users answer a survey, the 500 are the sample.

sample = [12, 15, 18]nprint(len(sample))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. A sample must represent the target population for generalisation.

3. Parameters and statistics

Concept and intuition: A parameter describes a population, such as μ; a statistic describes a sample, such as x̄, and estimates the parameter.

Formula or rule: A parameter describes a population, such as μ; a statistic describes a sample, such as x̄, and estimates the parameter. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: A sample mean x̄ = 72 estimates a population mean μ that is usually unknown.

import statisticsnprint(statistics.mean([70, 72, 74]))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Do not call a sample statistic a population fact without stating sampling uncertainty.

4. Types of data

Concept and intuition: Data may be structured or unstructured, primary or secondary, and numerical, categorical, text, image or event data.

Formula or rule: Data may be structured or unstructured, primary or secondary, and numerical, categorical, text, image or event data. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: A transaction amount is numerical, a payment method is categorical, and a review is text; each needs different summaries.

data = {"amount": 125.5, "method": "card"}nprint(data)

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Choose methods from the measurement process, not from column appearance alone.

5. Qualitative and quantitative variables

Concept and intuition: Qualitative variables describe categories; quantitative variables represent measurable amounts. Counts are discrete, measurements are often continuous.

Formula or rule: Qualitative variables describe categories; quantitative variables represent measurable amounts. Counts are discrete, measurements are often continuous. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Number of orders is a count; delivery time can take fractional values; city is qualitative.

orders = [2, 4, 3]nprint(sum(orders) / len(orders))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Do not average arbitrary category codes such as 1=Delhi and 2=Mumbai.

6. Nominal, ordinal, interval and ratio scales

Concept and intuition: Nominal labels have no order; ordinal labels have order but unequal gaps; interval scales have equal gaps but no meaningful zero; ratio scales have a true zero.

Formula or rule: Nominal labels have no order; ordinal labels have order but unequal gaps; interval scales have equal gaps but no meaningful zero; ratio scales have a true zero. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Temperature in Celsius is interval; income is ratio; satisfaction levels are ordinal.

levels = ["low", "medium", "high"]nprint(levels.index("high"))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. The scale determines valid arithmetic, summaries and visualisations.

7. Cross-sectional, time-series and panel data

Concept and intuition: Cross-sectional data observe many entities at one time; time series observe one process over time; panel data follow many entities over time.

Formula or rule: Cross-sectional data observe many entities at one time; time series observe one process over time; panel data follow many entities over time. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Sales for 1,000 customers in June are cross-sectional; daily sales for one shop are time series; daily sales for every shop are panel.

import pandas as pdndf = pd.DataFrame({"shop": ["A", "A", "B"], "day": [1, 2, 1]})nprint(df.shape)

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Respect dependence across time or entities; ordinary independent-sample formulas may fail.

8. Sampling techniques

Concept and intuition: Simple random, stratified, systematic, cluster and convenience sampling differ in how units are selected.

Formula or rule: Simple random, stratified, systematic, cluster and convenience sampling differ in how units are selected. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Stratifying by region and sampling within each region can ensure small regions are represented.

rng = np.random.default_rng(7)nprint(rng.choice(10, size=3, replace=False))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Document the frame, inclusion rule, sample size and selection probabilities.

9. Sampling bias and selection bias

Concept and intuition: Bias is systematic error from who is measured or how; sampling variability is random fluctuation and does not disappear by calling a biased sample large.

Formula or rule: Bias is systematic error from who is measured or how; sampling variability is random fluctuation and does not disappear by calling a biased sample large. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: A voluntary app survey can overrepresent highly engaged users even with 100,000 responses.

observed = np.array([90, 92, 95])nprint(observed.mean())

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Ask who is missing and whether response probability relates to the outcome.

Part B: descriptive statistics

10. Mean, median and mode

Concept and intuition: Mean is Σxᵢ/n, median is the middle ordered value, and mode is the most frequent value.

Formula or rule: Mean is Σxᵢ/n, median is the middle ordered value, and mode is the most frequent value. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: For [2, 3, 3, 100], mean=27, median=3 and mode=3; the outlier changes the mean dramatically.

import numpy as npnx = [2, 3, 3, 100]nprint(np.mean(x), np.median(x))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Choose a summary that reflects the distribution and the decision.

11. Range and interquartile range

Concept and intuition: Range=max−min; IQR=Q₃−Q₁ and describes the middle 50% robustly.

Formula or rule: Range=max−min; IQR=Q₃−Q₁ and describes the middle 50% robustly. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: For [1,2,3,4,100], the range is 99 while the IQR is much less affected by 100.

q1, q3 = np.percentile([1, 2, 3, 4, 100], [25, 75])nprint(q3 - q1)

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. State the percentile convention used by the software when samples are small.

12. Variance and standard deviation

Concept and intuition: Population variance σ²=Σ(xᵢ−μ)²/N; sample variance s²=Σ(xᵢ−x̄)²/(n−1); standard deviation is the square root.

Formula or rule: Population variance σ²=Σ(xᵢ−μ)²/N; sample variance s²=Σ(xᵢ−x̄)²/(n−1); standard deviation is the square root. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: For [2,4,6], x̄=4 and squared deviations sum to 8, so sample variance=4 and sample SD=2.

print(np.var([2, 4, 6], ddof=1), np.std([2, 4, 6], ddof=1))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Use ddof=1 for the usual unbiased sample variance estimate.

13. Percentiles and quartiles

Concept and intuition: The pth percentile is a value at or below which approximately p percent of observations fall; quartiles are the 25th, 50th and 75th percentiles.

Formula or rule: The pth percentile is a value at or below which approximately p percent of observations fall; quartiles are the 25th, 50th and 75th percentiles. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: The 90th percentile response time is 800 ms: about 90% of observed requests are no slower than 800 ms.

print(np.percentile([10, 20, 30, 40], 75))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Percentiles do not identify why the tail exists; inspect the full distribution.

14. Frequency distributions

Concept and intuition: A frequency distribution counts observations in categories or bins; relative frequency divides counts by n.

Formula or rule: A frequency distribution counts observations in categories or bins; relative frequency divides counts by n. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Bins 0–10, 10–20 and 20–30 reveal concentration that a mean hides.

counts, edges = np.histogram([2, 8, 12, 24], bins=[0, 10, 20, 30])nprint(counts)

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Choose bin widths transparently; changing bins can change the visual story.

15. Skewness

Concept and intuition: Skewness describes asymmetry. Positive skew has a long right tail; negative skew has a long left tail. A common moment coefficient is E[(X−μ)³]/σ³.

Formula or rule: Skewness describes asymmetry. Positive skew has a long right tail; negative skew has a long left tail. A common moment coefficient is E[(X−μ)³]/σ³. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Income often has positive skew, so median and quantiles may communicate typical income better than mean.

from scipy.stats import skewnprint(skew([1, 2, 2, 3, 10]))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Skewness is sample- and outlier-sensitive; do not treat it as a causal explanation.

16. Kurtosis

Concept and intuition: Kurtosis describes tail weight and peakedness; excess kurtosis subtracts 3 so a normal distribution has excess kurtosis 0.

Formula or rule: Kurtosis describes tail weight and peakedness; excess kurtosis subtracts 3 so a normal distribution has excess kurtosis 0. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: A high excess kurtosis indicates more extreme observations than a normal reference, not automatically a “better” or “worse” dataset.

from scipy.stats import kurtosisnprint(kurtosis([1, 2, 2, 3, 10]))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. State whether you report Pearson or excess kurtosis and the estimator convention.

17. Covariance

Concept and intuition: Cov(X,Y)=E[(X−μX)(Y−μY)] measures joint deviation and retains units, so magnitude depends on scale.

Formula or rule: Cov(X,Y)=E[(X−μX)(Y−μY)] measures joint deviation and retains units, so magnitude depends on scale. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: If study hours and marks rise together, covariance is positive; multiplying marks by 10 multiplies covariance by 10.

print(np.cov([1, 2, 3], [2, 4, 5], ddof=1)[0, 1])

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Covariance sign is useful, but magnitude is not comparable across differently scaled variables.

18. Correlation

Concept and intuition: Correlation standardises covariance: ρ=Cov(X,Y)/(σXσY), ranging from −1 to 1 for Pearson correlation.

Formula or rule: Correlation standardises covariance: ρ=Cov(X,Y)/(σXσY), ranging from −1 to 1 for Pearson correlation. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: r=0.8 indicates strong linear association in the sample, not that one variable causes the other.

print(np.corrcoef([1, 2, 3], [2, 4, 5])[0, 1])

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Inspect a scatterplot; nonlinear dependence can have Pearson correlation near zero.

19. Pearson and Spearman correlation

Concept and intuition: Pearson measures linear association on values; Spearman computes Pearson correlation on ranks and captures monotonic association.

Formula or rule: Pearson measures linear association on values; Spearman computes Pearson correlation on ranks and captures monotonic association. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: A monotonic but curved relationship may have high Spearman and lower Pearson correlation.

from scipy.stats import pearsonr, spearmanrnprint(pearsonr([1, 2, 3], [1, 4, 9]).statistic)nprint(spearmanr([1, 2, 3], [1, 4, 9]).statistic)

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Use Spearman for ordinal or strongly non-normal monotonic data, but explain ties and dependence.

20. Data visualization and distribution analysis

Concept and intuition: Histograms show distributions, boxplots show quartiles and outliers, scatterplots show relationships, and line charts show ordered time.

Formula or rule: Histograms show distributions, boxplots show quartiles and outliers, scatterplots show relationships, and line charts show ordered time. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: A boxplot can reveal a long tail; a scatterplot can reveal clusters that correlation averages away.

import matplotlib.pyplot as pltnplt.hist([1, 2, 2, 3, 10])nplt.xlabel("value")

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Label units, sample size and uncertainty; never infer a distribution from a decorative chart.

Part C: probability

21. Basic probability rules

Concept and intuition: Probability lies in [0,1], P(Aᶜ)=1−P(A), and the sample space contains all mutually exclusive outcomes.

Formula or rule: Probability lies in [0,1], P(Aᶜ)=1−P(A), and the sample space contains all mutually exclusive outcomes. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: For a fair die P(even)=3/6=0.5.

print(3 / 6)

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Define the event and sample space before applying a rule.

22. Addition and multiplication rules

Concept and intuition: P(A∪B)=P(A)+P(B)−P(A∩B); P(A∩B)=P(A|B)P(B). For disjoint events the intersection is zero.

Formula or rule: P(A∪B)=P(A)+P(B)−P(A∩B); P(A∩B)=P(A|B)P(B). For disjoint events the intersection is zero. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: If P(A)=.4, P(B)=.3 and P(A∩B)=.1, union probability=.6.

print(0.4 + 0.3 - 0.1)

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Do not add overlapping events without subtracting their intersection.

23. Conditional probability

Concept and intuition: P(A|B)=P(A∩B)/P(B), when P(B)>0. It updates the chance of A after learning B.

Formula or rule: P(A|B)=P(A∩B)/P(B), when P(B)>0. It updates the chance of A after learning B. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: If 30 of 100 customers are premium and 12 premium customers churn, P(churn|premium)=12/30=.4.

print(12 / 30)

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. P(A|B) and P(B|A) are different questions.

24. Independence

Concept and intuition: A and B are independent when P(A∩B)=P(A)P(B), equivalently P(A|B)=P(A).

Formula or rule: A and B are independent when P(A∩B)=P(A)P(B), equivalently P(A|B)=P(A). Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Two independent coin tosses remain independent; drawing without replacement usually creates dependence.

print(0.5 * 0.5)

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Never assume independence merely because variables are in different columns.

25. Bayes theorem

Concept and intuition: P(A|B)=P(B|A)P(A)/P(B). It combines a prior, likelihood and evidence.

Formula or rule: P(A|B)=P(B|A)P(A)/P(B). It combines a prior, likelihood and evidence. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: With disease prevalence .01, sensitivity .9 and false-positive rate .05, P(disease|positive)=.009/.059≈.153.

prior, sens, fp = .01, .9, .05nprint(sens * prior / (sens * prior + fp * (1 - prior)))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Base rates matter; a highly accurate test can have many false positives in a low-prevalence population.

26. Random variables

Concept and intuition: A random variable maps outcomes to numbers. Its expectation is E[X]=Σxp(x) for discrete X or ∫xf(x)dx for continuous X.

Formula or rule: A random variable maps outcomes to numbers. Its expectation is E[X]=Σxp(x) for discrete X or ∫xf(x)dx for continuous X. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: For a fair die E[X]=(1+…+6)/6=3.5.

print(sum(range(1, 7)) / 6)

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Distinguish a random variable from one realised observation.

27. Discrete and continuous distributions

Concept and intuition: Discrete variables assign probability mass to countable values; continuous variables use a density and individual points have probability zero.

Formula or rule: Discrete variables assign probability mass to countable values; continuous variables use a density and individual points have probability zero. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Orders per hour are discrete; delivery duration is continuous even if recorded to whole minutes.

from scipy.stats import poissonnprint(poisson.pmf(2, 3))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. A density height is not a probability; integrate over an interval.

28. Bernoulli and binomial distributions

Concept and intuition: Bernoulli models one success with probability p; Binomial(n,p) counts successes in n independent trials: P(X=k)=C(n,k)pᵏ(1−p)ⁿ⁻ᵏ.

Formula or rule: Bernoulli models one success with probability p; Binomial(n,p) counts successes in n independent trials: P(X=k)=C(n,k)pᵏ(1−p)ⁿ⁻ᵏ. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: For n=10,p=.2, expected successes=np=2 and P(X=2)=C(10,2).2².8⁸.

from scipy.stats import binomnprint(binom.pmf(2, 10, .2))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Binomial requires fixed n, common p and independent trials; clustered users violate this easily.

29. Poisson distribution

Concept and intuition: Poisson(λ) models counts in a fixed interval when events occur independently at a constant rate: P(X=k)=e⁻λ λᵏ/k!.

Formula or rule: Poisson(λ) models counts in a fixed interval when events occur independently at a constant rate: P(X=k)=e⁻λ λᵏ/k!. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: If support receives λ=3 tickets per hour, P(exactly 2)=e⁻³3²/2!.

from scipy.stats import poissonnprint(poisson.pmf(2, 3))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Check for overdispersion and changing rates; a Poisson variance equals its mean.

30. Uniform distribution

Concept and intuition: For X~Uniform(a,b), density is 1/(b−a), mean=(a+b)/2 and variance=(b−a)²/12.

Formula or rule: For X~Uniform(a,b), density is 1/(b−a), mean=(a+b)/2 and variance=(b−a)²/12. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: A random value uniformly selected from 0 to 10 has mean 5.

from scipy.stats import uniformnprint(uniform.mean(loc=0, scale=10))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Uniformity is an assumption about equal density, not merely a bounded range.

31. Normal distribution

Concept and intuition: The normal distribution is symmetric with mean μ and variance σ²; standardisation is Z=(X−μ)/σ.

Formula or rule: The normal distribution is symmetric with mean μ and variance σ²; standardisation is Z=(X−μ)/σ. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: For μ=100, σ=15, X=130 gives z=2, two standard deviations above the mean.

from scipy.stats import normnprint(norm.cdf(2))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Normality of raw data is not required for every method; often the sampling distribution or residuals matter.

32. Exponential distribution

Concept and intuition: Exponential(λ) models waiting time between Poisson events, with mean 1/λ and survival P(X>t)=e⁻λᵗ.

Formula or rule: Exponential(λ) models waiting time between Poisson events, with mean 1/λ and survival P(X>t)=e⁻λᵗ. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: At λ=.5 per hour, expected wait is 2 hours and P(wait>2)=e⁻¹.

from scipy.stats import exponnprint(expon.sf(2, scale=2))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. The memoryless property is strong; real service times may need other distributions.

33. Central Limit Theorem

Concept and intuition: For sufficiently large independent observations with finite variance, the sample mean is approximately normal with mean μ and standard error σ/√n.

Formula or rule: For sufficiently large independent observations with finite variance, the sample mean is approximately normal with mean μ and standard error σ/√n. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: A skewed customer-spend population can still produce approximately normal sample means when n is adequate.

sample = np.random.default_rng(1).exponential(size=(1000, 50)).mean(axis=1)nprint(sample.mean())

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. “Large enough” depends on skew, dependence and the statistic; inspect simulation and diagnostics.

34. Law of Large Numbers

Concept and intuition: As sample size grows, the sample average converges to the expected value under suitable conditions.

Formula or rule: As sample size grows, the sample average converges to the expected value under suitable conditions. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Repeated fair-die averages tend toward 3.5, but a short run can differ substantially.

rng = np.random.default_rng(2)nprint(rng.integers(1, 7, 100000).mean())

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Convergence does not guarantee an unbiased sampling process or eliminate systematic bias.

Part D: inferential statistics

These inferential methods make Statistics for Data Science useful for testing assumptions, measuring uncertainty and interpreting results from real datasets.

35. Sampling distributions

Concept and intuition: A sampling distribution is the distribution of a statistic over repeated samples. It quantifies estimator variability.

Formula or rule: A sampling distribution is the distribution of a statistic over repeated samples. It quantifies estimator variability. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: The sampling distribution of x̄ has standard deviation σ/√n when observations are independent.

means = [np.mean(np.random.default_rng(i).normal(size=30)) for i in range(1000)]nprint(np.std(means, ddof=1))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Do not confuse a data distribution with a statistic’s sampling distribution.

36. Standard error

Concept and intuition: Standard error estimates the standard deviation of an estimator; for a mean it is s/√n.

Formula or rule: Standard error estimates the standard deviation of an estimator; for a mean it is s/√n. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: s=10 and n=25 gives SE=2. A larger sample narrows uncertainty, not necessarily bias.

x = np.array([10, 12, 14, 16, 18])nprint(x.std(ddof=1) / np.sqrt(len(x)))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. SE is not the standard deviation of individual observations.

37. Point and interval estimation

Concept and intuition: A point estimate is one value such as x̄; an interval estimate gives a range produced by a procedure with stated coverage.

Formula or rule: A point estimate is one value such as x̄; an interval estimate gives a range produced by a procedure with stated coverage. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Estimate mean delivery time as 4.2 days with a 95% confidence interval [3.8,4.6].

import scipy.stats as stnprint(st.t.interval(.95, len(x)-1, loc=x.mean(), scale=st.sem(x)))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Intervals express procedure uncertainty; they do not assign a probability to a fixed parameter after the data are observed.

38. Confidence intervals

Concept and intuition: A common mean interval is x̄ ± critical value × SE. A 95% method captures the true parameter in about 95% of repeated samples under assumptions.

Formula or rule: A common mean interval is x̄ ± critical value × SE. A 95% method captures the true parameter in about 95% of repeated samples under assumptions. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: For x̄=50, SE=2 and t*=2.1, interval is [45.8,54.2].

print((50 - 2.1 * 2, 50 + 2.1 * 2))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Interpret coverage correctly and report effect size, units and design.

39. Hypothesis testing

Concept and intuition: Testing compares data with a null model. Define H₀, H₁, test statistic, rejection rule, assumptions and practical decision before seeing results.

Formula or rule: Testing compares data with a null model. Define H₀, H₁, test statistic, rejection rule, assumptions and practical decision before seeing results. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: H₀: new conversion rate equals old rate; H₁: it differs. A small p-value is evidence against H₀, not proof of H₁.

from scipy.stats import ttest_1sampnprint(ttest_1samp([51, 49, 52, 50], 50))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. A test cannot repair biased sampling or poor outcome definition.

40. Null and alternative hypotheses

Concept and intuition: H₀ represents a reference value or no-effect claim; H₁ represents a directional or two-sided alternative.

Formula or rule: H₀ represents a reference value or no-effect claim; H₁ represents a directional or two-sided alternative. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: A one-sided test H₁: μ>10 should be chosen before data and only when lower values are not the decision concern.

print("H0: mu = 10; H1: mu != 10")

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Do not switch from two-sided to one-sided after seeing the direction.

41. Type I and Type II errors

Concept and intuition: Type I rejects a true H₀ with probability α; Type II fails to reject a false H₀ with probability β. Power is 1−β.

Formula or rule: Type I rejects a true H₀ with probability α; Type II fails to reject a false H₀ with probability β. Power is 1−β. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: With α=.05, a false alarm rate is controlled at 5% under the model, while low power can miss a meaningful effect.

alpha = 0.05nbeta = 0.20nprint(1 - beta)

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. “Fail to reject” is not proof that H₀ is true.

42. Statistical power

Concept and intuition: Power depends on effect size, variability, sample size and α. Larger n or a larger true effect generally increases power.

Formula or rule: Power depends on effect size, variability, sample size and α. Larger n or a larger true effect generally increases power. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: A study designed to detect a 5-point lift may have low power for a 1-point lift even if the 1-point lift matters operationally.

from statsmodels.stats.power import TTestIndPowernprint(TTestIndPower().solve_power(effect_size=.5, alpha=.05, power=.8))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Plan sample size before looking at outcomes; distinguish detectable from practically important effects.

43. p-values

Concept and intuition: A p-value is the probability, under H₀ and the test assumptions, of a result at least as extreme as observed.

Formula or rule: A p-value is the probability, under H₀ and the test assumptions, of a result at least as extreme as observed. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: p=.03 means the result is relatively unusual under H₀; it does not mean there is a 97% chance the effect is real.

from scipy.stats import ttest_1sampnprint(ttest_1samp([52, 53, 49, 51], 50).pvalue)

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Never interpret p-value without effect size, interval, sample size and design.

44. z-test

Concept and intuition: A z-test uses a normal reference, often when population σ is known or large-sample approximations apply: z=(x̄−μ₀)/(σ/√n).

Formula or rule: A z-test uses a normal reference, often when population σ is known or large-sample approximations apply: z=(x̄−μ₀)/(σ/√n). Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: x̄=102, μ₀=100, σ=10,n=100 gives z=2.

from scipy.stats import normnprint(2 * norm.sf(2))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Known σ is uncommon; using a z-test with estimated σ in a small sample can understate uncertainty.

45. One-sample and two-sample t-tests

Concept and intuition: A one-sample t-test compares one mean with μ₀; an independent two-sample test compares group means, commonly using Welch’s unequal-variance version.

Formula or rule: A one-sample t-test compares one mean with μ₀; an independent two-sample test compares group means, commonly using Welch’s unequal-variance version. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Compare average wait time with a target or compare treatment and control means with independent users.

from scipy.stats import ttest_indnprint(ttest_ind([10, 11, 9], [8, 9, 10], equal_var=False))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Check independence and define the estimand; Welch avoids assuming equal variances.

46. Paired t-test

Concept and intuition: A paired test analyses within-unit differences, reducing noise from stable individual characteristics: t=d̄/(s_d/√n).

Formula or rule: A paired test analyses within-unit differences, reducing noise from stable individual characteristics: t=d̄/(s_d/√n). Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Measure each student before and after training and test the distribution of paired improvements.

from scipy.stats import ttest_relnprint(ttest_rel([60, 70, 80], [65, 72, 84]))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Pairs must be meaningful and differences approximately suitable for the t method.

47. Chi-square test

Concept and intuition: Chi-square tests independence in a contingency table using Σ(O−E)²/E, or tests goodness of fit against expected counts.

Formula or rule: Chi-square tests independence in a contingency table using Σ(O−E)²/E, or tests goodness of fit against expected counts. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Compare payment method and region; expected counts derive from marginal totals under independence.

from scipy.stats import chi2_contingencynprint(chi2_contingency([[20, 10], [10, 20]]).pvalue)

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Small expected counts can invalidate the approximation; combine categories or use an exact method.

48. ANOVA

Concept and intuition: One-way ANOVA tests whether several group means are equal using F=between-group variation/within-group variation.

Formula or rule: One-way ANOVA tests whether several group means are equal using F=between-group variation/within-group variation. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Compare mean scores across three teaching methods; a significant F says at least one mean differs, not which pair.

from scipy.stats import f_onewaynprint(f_oneway([8, 9], [10, 11], [8, 10]))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Check independence, residual normality and variance homogeneity; follow a significant result with corrected comparisons.

49. Non-parametric tests

Concept and intuition: Mann–Whitney, Wilcoxon signed-rank, Kruskal–Wallis and permutation tests reduce distributional assumptions, but test different features such as ranks or distributions.

Formula or rule: Mann–Whitney, Wilcoxon signed-rank, Kruskal–Wallis and permutation tests reduce distributional assumptions, but test different features such as ranks or distributions. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Use Mann–Whitney for independent ordinal outcomes when a mean comparison is not defensible.

from scipy.stats import mannwhitneyunprint(mannwhitneyu([1, 2, 3], [4, 5, 6]))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Non-parametric does not mean assumption-free; independence and sampling design still matter.

50. Multiple testing and correction

Concept and intuition: Testing m hypotheses inflates the chance of false positives. Bonferroni uses α/m; Benjamini–Hochberg controls expected false discovery rate under conditions.

Formula or rule: Testing m hypotheses inflates the chance of false positives. Bonferroni uses α/m; Benjamini–Hochberg controls expected false discovery rate under conditions. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: With α=.05 and 10 planned tests, Bonferroni threshold is .005.

from statsmodels.stats.multitest import multipletestsnprint(multipletests([.001, .02, .4], method="fdr_bh")[1])

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Pre-register hypotheses where possible and report all tested outcomes, not only significant ones.

Part E: relationships and modeling

51. Correlation versus causation

Concept and intuition: Correlation describes association; causation requires a credible intervention or design that rules out confounding, reverse causality and selection effects.

Formula or rule: Correlation describes association; causation requires a credible intervention or design that rules out confounding, reverse causality and selection effects. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Ice-cream sales and temperature correlate because temperature influences both; ice cream does not cause hot weather.

print(np.corrcoef([20, 25, 30], [2, 3, 5])[0, 1])

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Ask what would change under intervention and identify a causal diagram or randomization strategy.

52. Simple linear regression

Concept and intuition: The model y=β₀+β₁x+ε estimates an average change β₁ in y per unit x. Least squares minimizes Σ residual².

Formula or rule: The model y=β₀+β₁x+ε estimates an average change β₁ in y per unit x. Least squares minimizes Σ residual². Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: β₁=2 means one additional study hour is associated with two more marks on average, within the observed range.

from scipy.stats import linregressnprint(linregress([1, 2, 3], [2, 4, 5]).slope)

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Association is not causal; inspect residuals and avoid extrapolating beyond observed x.

53. Multiple linear regression

Concept and intuition: Multiple regression estimates y=β₀+β₁x₁+…+βₖxₖ+ε, where a coefficient is the conditional association holding included predictors fixed.

Formula or rule: Multiple regression estimates y=β₀+β₁x₁+…+βₖxₖ+ε, where a coefficient is the conditional association holding included predictors fixed. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: A salary coefficient for experience is conditional on education and location only if those variables are correctly measured and included.

import statsmodels.api as smnX = sm.add_constant([[1, 2], [2, 1], [3, 4]])nprint(sm.OLS([3, 4, 7], X).fit().params)

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Coefficients depend on coding, scale, omitted variables and collinearity; do not call them causal automatically.

54. Regression assumptions

Concept and intuition: Common assumptions concern linearity, independent errors, constant variance, appropriate conditional mean and, for small-sample inference, error normality.

Formula or rule: Common assumptions concern linearity, independent errors, constant variance, appropriate conditional mean and, for small-sample inference, error normality. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: A residual fan shape suggests heteroscedasticity; clusters over time suggest dependence.

import statsmodels.api as smnmodel = sm.OLS([1, 2, 3], sm.add_constant([1, 2, 3])).fit()nprint(model.resid)

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Inspect residuals rather than checking assumptions only on raw predictors.

55. Residual analysis

Concept and intuition: Residuals eᵢ=yᵢ−ŷᵢ show unexplained differences. Plot residuals against fitted values, predictors and time; inspect leverage and influential points.

Formula or rule: Residuals eᵢ=yᵢ−ŷᵢ show unexplained differences. Plot residuals against fitted values, predictors and time; inspect leverage and influential points. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: A curved residual pattern suggests a missing nonlinear term or transformation.

print(np.array([10, 12, 15]) - np.array([9, 13, 14]))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Outliers may be data errors, rare valid cases or influential observations; investigate before deleting.

56. Multicollinearity

Concept and intuition: Multicollinearity means predictors contain overlapping information, inflating coefficient uncertainty and making individual effects unstable.

Formula or rule: Multicollinearity means predictors contain overlapping information, inflating coefficient uncertainty and making individual effects unstable. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Height in centimetres and height in metres are perfectly collinear; keep one representation.

from statsmodels.stats.outliers_influence import variance_inflation_factornprint("VIF is assessed per design matrix column")

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. High VIF is a diagnostic, not an automatic deletion rule; consider domain choice, regularisation and prediction goals.

57. Logistic regression from a statistical perspective

Concept and intuition: Logistic regression models log odds: log(p/(1−p))=β₀+βᵀx. exp(βⱼ) is an odds ratio for a one-unit predictor change holding others fixed.

Formula or rule: Logistic regression models log odds: log(p/(1−p))=β₀+βᵀx. exp(βⱼ) is an odds ratio for a one-unit predictor change holding others fixed. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: β=0.69 implies an odds ratio about 2, not a probability increase of 69 percentage points.

import numpy as npnprint(np.exp(.69))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Odds are not probabilities; report predicted probabilities at meaningful covariate values.

58. Goodness of fit

Concept and intuition: Goodness-of-fit compares model predictions with observed outcomes using residual diagnostics, R² with care, likelihood measures, calibration and held-out performance.

Formula or rule: Goodness-of-fit compares model predictions with observed outcomes using residual diagnostics, R² with care, likelihood measures, calibration and held-out performance. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: A high training R² can coexist with poor test error when the model overfits.

from sklearn.metrics import r2_scorenprint(r2_score([1, 2, 3], [1, 2, 2.5]))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. No single fit statistic proves a model is useful; combine diagnostics with the decision objective.

Part F: experimentation

59. A/B testing

Concept and intuition: An A/B test randomly assigns units to control or treatment and estimates a difference in an outcome under a pre-specified analysis.

Formula or rule: An A/B test randomly assigns units to control or treatment and estimates a difference in an outcome under a pre-specified analysis. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: If conversion is 10% versus 12%, estimate the absolute lift (2 percentage points), relative lift (20%) and interval.

from statsmodels.stats.proportion import proportions_ztestnprint(proportions_ztest([12, 10], [100, 100]))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Define primary metric, guardrails, exposure unit and stopping rule before launch.

60. Control and treatment groups

Concept and intuition: Control estimates the counterfactual baseline; treatment receives the intervention. Their comparability depends on assignment and implementation.

Formula or rule: Control estimates the counterfactual baseline; treatment receives the intervention. Their comparability depends on assignment and implementation. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: A control sees the existing checkout and treatment sees the new checkout; users, not page views, may be the unit.

control = np.array([0, 1, 0])ntreatment = np.array([1, 1, 0])nprint(treatment.mean() - control.mean())

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Avoid contamination, unequal exposure and treatment misclassification.

61. Randomization

Concept and intuition: Randomization makes treatment assignment independent of potential outcomes in expectation, balancing measured and unmeasured confounders over repeated experiments.

Formula or rule: Randomization makes treatment assignment independent of potential outcomes in expectation, balancing measured and unmeasured confounders over repeated experiments. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: A seeded random assignment is reproducible for analysis, but the seed must not create predictable production assignment.

rng = np.random.default_rng(3)nprint(rng.permutation(["control", "treatment", "control"]))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Check balance and implementation, but do not “adjust away” randomization by selecting favourable subgroups.

62. Sample-size considerations

Concept and intuition: Sample size depends on baseline rate or variance, minimum detectable effect, α, desired power, allocation and attrition.

Formula or rule: Sample size depends on baseline rate or variance, minimum detectable effect, α, desired power, allocation and attrition. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Detecting a 1 percentage-point lift needs much more traffic than detecting a 10-point lift at the same noise level.

from statsmodels.stats.power import NormalIndPowernprint("Use a proportion power calculation for binary outcomes")

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Power calculations are planning assumptions, not guarantees; include practical traffic and duration constraints.

63. Confounding variables

Concept and intuition: A confounder relates to treatment and outcome and creates a spurious or distorted association when assignment is not random.

Formula or rule: A confounder relates to treatment and outcome and creates a spurious or distorted association when assignment is not random. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Marketing channel may affect both who receives a feature and conversion; randomization or careful adjustment addresses it.

print("Draw treatment <- channel -> outcome before modelling")

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Do not adjust for post-treatment mediators without a causal estimand.

64. Experimental design

Concept and intuition: Design specifies units, randomization, blocking/stratification, factorial factors, outcomes, duration, exclusion rules and analysis.

Formula or rule: Design specifies units, randomization, blocking/stratification, factorial factors, outcomes, duration, exclusion rules and analysis. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Block by country when country strongly affects conversion, then randomize within blocks to improve precision.

design = {"unit": "user", "primary_metric": "conversion", "alpha": .05}nprint(design)

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. A design document prevents metric switching and peeking-driven decisions.

65. Interpreting experiment outcomes

Concept and intuition: Interpret estimate, confidence interval, practical threshold, heterogeneity, guardrails, data quality and implementation before shipping.

Formula or rule: Interpret estimate, confidence interval, practical threshold, heterogeneity, guardrails, data quality and implementation before shipping. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: A statistically significant 0.1% lift may be operationally irrelevant or outweighed by a latency regression.

effect = .12 - .10nprint(effect, effect / .10)

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Separate evidence about this experiment from claims about all future users.

Part G: time-series statistics

66. Trend and seasonality

Concept and intuition: Trend is long-term movement; seasonality is a repeating calendar pattern. Decompose observed yₜ into level/trend, seasonal and residual components.

Formula or rule: Trend is long-term movement; seasonality is a repeating calendar pattern. Decompose observed yₜ into level/trend, seasonal and residual components. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Retail sales may rise over years and repeat every December; remove or model both before evaluating shocks.

import pandas as pdnseries = pd.Series([10, 12, 11, 15])nprint(series.diff().tolist())

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Do not call every change a trend; plot sufficient history and compare comparable periods.

67. Stationarity

Concept and intuition: A weakly stationary series has stable mean, variance and autocovariance over time. Many ARIMA methods require stationarity after differencing or transformation.

Formula or rule: A weakly stationary series has stable mean, variance and autocovariance over time. Many ARIMA methods require stationarity after differencing or transformation. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: A random walk has changing level and is non-stationary; first differences may be stationary.

series = pd.Series([10, 12, 13, 16])nprint(series.diff().dropna().tolist())

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Stationarity is about the process, not simply a flat-looking short plot.

68. ACF and PACF

Concept and intuition: ACF measures correlation at lags; PACF measures correlation at a lag after accounting for shorter lags. Their patterns guide AR and MA orders.

Formula or rule: ACF measures correlation at lags; PACF measures correlation at a lag after accounting for shorter lags. Their patterns guide AR and MA orders. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: A slowly decaying ACF may indicate persistence or non-stationarity; a PACF cutoff can suggest an AR order.

from statsmodels.tsa.stattools import acf, pacfnprint(acf([1, 2, 1, 2, 1], nlags=2))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Confidence bands and sample size matter; do not select a model from a plot alone.

69. Autocorrelation

Concept and intuition: Autocorrelation is correlation between a series and lagged versions of itself. Positive autocorrelation means nearby values tend to move together.

Formula or rule: Autocorrelation is correlation between a series and lagged versions of itself. Positive autocorrelation means nearby values tend to move together. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Ignoring daily dependence can make standard errors too small and false significance more likely.

print(pd.Series([1, 2, 3, 2]).autocorr(lag=1))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Use time-aware splits and residual diagnostics; random shuffling can leak future information.

70. White noise

Concept and intuition: White noise has zero mean, constant variance and no autocorrelation; a good forecast residual should resemble white noise.

Formula or rule: White noise has zero mean, constant variance and no autocorrelation; a good forecast residual should resemble white noise. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: A residual series with a visible pattern means the model left predictable structure.

from statsmodels.stats.diagnostic import acorr_ljungboxnprint(acorr_ljungbox([1, -1, 1, -1], lags=[1]))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. A non-significant test does not prove perfect white noise; inspect plots and multiple lags.

71. ADF test

Concept and intuition: The Augmented Dickey–Fuller test has a unit-root null. A small p-value provides evidence against a unit root, subject to lag, trend and sample choices.

Formula or rule: The Augmented Dickey–Fuller test has a unit-root null. A small p-value provides evidence against a unit root, subject to lag, trend and sample choices. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Rejecting the ADF null supports stationarity under the specified model; failing to reject is not proof of a unit root.

from statsmodels.tsa.stattools import adfullernprint(adfuller([1, 2, 1, 2, 1])[1])

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Choose regression terms and lag length deliberately; structural breaks can mislead the test.

72. KPSS test

Concept and intuition: KPSS reverses the usual framing: its null is level or trend stationarity. A small p-value is evidence against stationarity.

Formula or rule: KPSS reverses the usual framing: its null is level or trend stationarity. A small p-value is evidence against stationarity. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: Using ADF and KPSS together gives complementary evidence rather than a mechanical verdict.

from statsmodels.tsa.stattools import kpssnprint(kpss([1, 2, 1, 2, 1], regression="c", nlags="auto")[1])

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. State whether testing level or trend stationarity and do not treat p-values as binary truth machines.

73. AR, MA, ARMA and ARIMA basics

Concept and intuition: AR(p) uses lagged values; MA(q) uses lagged shocks; ARMA combines both for stationary series; ARIMA(p,d,q) differences d times before ARMA modelling.

Formula or rule: AR(p) uses lagged values; MA(q) uses lagged shocks; ARMA combines both for stationary series; ARIMA(p,d,q) differences d times before ARMA modelling. Let the symbols be defined by the data and design; write the estimand before calculating it.

Worked example: AR(1): yₜ=c+φyₜ₋₁+εₜ. If |φ|<1, the simple process is stationary around a stable mean.

from statsmodels.tsa.arima.model import ARIMAnmodel = ARIMA([10, 11, 10, 12, 11], order=(1, 1, 0)).fit()nprint(model.forecast(1))

Interpretation: Run the example and state what the output means in the units of the problem. A numerical result is conditional on the sampling, measurement and model assumptions.

Assumptions: identify independence, representative sampling, appropriate scale, distributional conditions and missing-data mechanisms relevant to this topic. Common mistake: applying a familiar formula without checking its assumptions or confusing association with causation.

Practice and solution: change one input and calculate the result by hand, then verify it in Python. The solution should show the formula, substitute the values, report units, explain uncertainty and include an edge-case check. Use time-ordered validation, compare against a naïve baseline and inspect residuals; do not tune on the test period.

Comparison tables and revision

Comparison Use the first when Use the second when Important caution
Mean vs median Distribution is reasonably symmetric and the arithmetic average is meaningful. Data are skewed or contain influential outliers. Report quantiles or a plot as context.
Variance vs standard deviation You need algebraic decomposition or model derivations. You want spread in the original units. Variance is squared units; sample variance uses n−1.
Covariance vs correlation You need a scale-dependent joint variation. You need a dimensionless, comparable linear association. Neither alone establishes causation.
z-test vs t-test Population σ is known or a justified large-sample approximation applies. σ is estimated, especially with a smaller sample. Design and independence matter more than naming the test.
Parametric vs non-parametric A meaningful model for means/distributions is defensible. Rank/permutation methods better match scale or robustness needs. Non-parametric tests still have assumptions.
ADF vs KPSS You want a unit-root null. You want a stationarity null. Use together with plots and domain knowledge.

Final revision checklist

  • Define population, sample, unit, parameter and estimand.
  • Classify variable scale before choosing arithmetic or plots.
  • Inspect distribution, missingness, outliers and dependence.
  • Distinguish standard deviation from standard error.
  • Interpret confidence intervals and p-values without probability errors.
  • Report effect size and practical importance beside significance.
  • Check assumptions, residuals and sensitivity analyses.
  • Explain randomization, confounding, power and multiple testing.
  • Use time-aware validation and avoid future leakage.
  • State the limitations of every conclusion.

Practice capstone

Take a public dataset and submit a notebook with a data dictionary, sampling discussion, descriptive table, distribution plots, one interval estimate, one justified test, an effect-size interpretation, a regression or experiment plan, diagnostics, and a limitations section. Use the Data Science roadmap, Python for Data Science guide and Machine Learning Fundamentals guide for the next step.

References: NIST/SEMATECH e-Handbook of Statistical Methods, SciPy statistics reference, statsmodels statistics documentation, NumPy statistics, pandas documentation.