…
…
Statistics and Data Analysis Fundamentals · Lesson 32 / 44 · Inference with formulas
PreviewIn this lesson you will
ttest_1samp, t.interval) and a Welch t interval and test for the difference between two independent group means (ttest_ind(..., equal_var=False)), and compare the result with the bootstrap and permutation test resultsYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The logistics manager comes to the meeting with two questions: "Our satisfaction target is 4 points. Do we reach it?" and "Are the customers of orders sent with Arrow Express really happier than the customers of Caravan Freight?" The bootstrap in lesson 30 and the permutation test in lesson 29 can answer these questions. In this lesson you will reach the same answers with a few lines of formula, and you will put the two ways side by side.
At the end of this lesson you will write these two lines to the manager:
In lesson 30 you found the interval in the first line, 3.84 to 4.02, with a bootstrap. In this lesson you will find the same interval and the same tests with ready-made SciPy functions, without thousands of repeats.
In this lesson you will:
In lesson 31 you saw one pattern for a proportion: estimate ± critical value × standard error. For a proportion, the standard error comes from the proportion itself: if the return rate is 0.072, you write √(0.072 × 0.928 / 885), and you need no other information. The critical value comes from the normal model too: 1.96 for 95%.
For a mean, the situation is a little different. In lesson 26 you saw that the standard error of the mean is σ / √n, where σ is the standard deviation of the population. We cannot see the population, so we do not know σ either. The only thing we can do is put the sample standard deviation (s) in its place: standard error ≈ s / √n. For satisfaction, s = 0.829 and n = 300, so the standard error is 0.829 / √300 = 0.0479.
But s also comes from the sample, so it also moves: another 300 customers would give a slightly different s. So now we estimate two things, both the mean and the spread. To account for this extra uncertainty, the critical value is taken a little larger than 1.96. These larger critical values come from the t distribution. The t distribution looks like the normal curve: it has a peak in the middle and is symmetric. But its tails are a little thicker, which means it gives a bit more probability to extreme values. The thickness depends on one number: the
In lesson 30, the bootstrap interval for the mobile − desktop satisfaction difference was −0.151 to 0.235. With the Welch formula:
import pandas as pd from scipy import stats a = pd.read_csv("survey.csv") mobile = a.loc[a["device"] == "mobile", "satisfaction"] desktop = a.loc[a["device"] == "desktop", "satisfaction"] result = stats.ttest_ind(mobile, desktop, equal_var=False) ci = result.confidence_interval() print("Difference:", round(mobile.mean() - desktop.mean(), 3), "| p:", round(result.pvalue, 3)) print("95% Welch interval:", round(ci.low, 3), "-", round(ci.high, 3))
OutputDifference: 0.044 | p: 0.653
95% Welch interval: -0.147 - 0.234The Welch interval (−0.147 to 0.234) is almost the same as the bootstrap interval. With p = 0.65, there is no evidence that satisfaction differs between the two devices. The scores are from 1 to 5 and only slightly skewed, and each group has more than 120 customers, so the conditions are comfortable.
Bazaar's site says "delivered in 3 days on average". Let's test it with the delivery times of the 851 delivered orders:
pandas pd scipy stats s = pd.read_csv() days = s[].dropna() result = stats.ttest_1samp(days, 3) ci = result.confidence_interval() (, (days), , (days.mean(), 3)) (, (result.statistic, 2), , (result.pvalue, 3)) (, (ci.low, 3), , (ci.high, 3))
Rounding a very small p-value and reporting it as "p = 0". When we round the p for Arrow Express and Caravan Freight to three decimal places:
import pandas as pd from scipy import stats a = pd.read_csv("survey.csv") h = a.loc[a["carrier"] == "Arrow Express", "satisfaction"] k = a.loc[a["carrier"] == "Caravan Freight", "satisfaction"] result = stats.ttest_ind(h, k, equal_var=False) print("p:", round(result.pvalue, 3)) print("p:", result.pvalue) print("p:", f"{result.pvalue:.1e}")
Outputp: 0.0
p: 1.4955197148813486e-05
p: 1.5e-05The first line reads like "p = 0", but p is never exactly 0: even if H₀ were true, a difference this extreme could still be seen with a very small probability. The real value is 0.000015. In a report, either write this number (f"{p:.1e}" gives it as 1.5e-05 with two significant digits) or say "p < 0.001".
stats.t.interval(0.95, n - 1, loc=mean, scale=stats.sem(x)) and stats.ttest_1samp(x, claim), and scale gets the standard error, not the standard deviation.stats.ttest_ind(x, y, equal_var=False) (Welch), and its interval comes from confidence_interval(); the results are very close to the bootstrap and the permutation test (satisfaction 3.836–4.024 and 3.837–4.020; Arrow Express − Caravan Freight difference 0.30–0.76, and p < 1/10,000 in the permutation test).Next lesson: Does a small p-value mean a big difference? You will see the two types of error, power, and effect size.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
| n | Degrees of freedom | 95% t critical value |
|---|---|---|
| 5 | 4 | 2.776 |
| 10 | 9 | 2.262 |
| 30 | 29 | 2.045 |
| 300 | 299 | 1.968 |
| (normal) | 1.960 |
The story of the t distribution starts in a beer factory. At the beginning of the 20th century, William Gosset worked at the Guinness factory in Dublin, and he had to judge the quality of barley and yeast with a few samples. With so little data, the intervals from the normal model were too optimistic. Gosset calculated the correct critical values and published them in 1908 under the pen name "Student". This is why it is still called the "Student t distribution" today.
You get the critical value from SciPy without looking at a table: stats.t.ppf(0.975, n - 1). The logic is the same as stats.norm.ppf in lesson 26: the value with an area of 0.975 on its left, which means the limit that cuts 2.5% from each of the two tails. Below, change n and the confidence level. The last line shows how far the interval reaches on each side of the mean for data with s = 0.83 points:
How do the sample size (n) and the confidence level change the t critical value and the half-width of the interval? (s = 0.83 points)
Pick a value; predict the output first, then look.
1from scipy import stats2confidence = 0.953n = 304s = 0.835tail = 1 - (1 - confidence) / 26t_critical = stats.t.ppf(tail, n - 1)7z_critical = stats.norm.ppf(tail)8print("n =", n, "| confidence:", confidence)9print("t critical:", round(t_critical, 3), "| normal:", round(z_critical, 3))10print("Interval: mean ±", round(t_critical * s / n ** 0.5, 3))
n = 30 | confidence: 0.95 t critical: 2.045 | normal: 1.96 Interval: mean ± 0.31
Faded lines didn't run with this value. Little data, wide net: at n = 5, the t critical value is 2.78, clearly larger than the normal 1.96; at n = 300, the difference is only 0.008. The interval gets narrower for two reasons: the critical value gets smaller, and the standard error (s / √n) gets smaller. 99% confidence widens the interval at every n. With n = 5, the 99% interval reaches 1.7 points on each side of the mean: on a rating scale from 1 to 5, it says almost nothing.
Let's clear up a common misunderstanding here: "The t distribution is for small samples, and you use the normal for large samples." In fact, whenever you estimate the spread from the sample, the correct critical value comes from t. With a large n, t and the normal are almost the same, so it does not matter which one you use; with a small n, the normal gives intervals that are too narrow. This is why always using t for means is a safe default.
The pattern is the same as in lesson 31, with only two parts changed: the standard error is s / √n, and the critical value comes from t. For satisfaction, the calculation is as follows (Example 1):
Let's do the same calculation with code. The SciPy function stats.sem(x) gives the standard error of the mean directly; it should match what we calculated by hand:
import pandas as pd from scipy import stats x = pd.read_csv("survey.csv")["satisfaction"] n = len(x) mean = x.mean() se = x.std() / n ** 0.5 t_critical = stats.t.ppf(0.975, n - 1) print("n:", n, "| mean:", round(mean, 2), "| s:", round(x.std(), 3)) print("Standard error:", round(se, 4), "| stats.sem:", round(stats.sem(x), 4)) print("t critical:", round(t_critical, 3)) print("95% interval:", round(mean - t_critical * se, 3), "-", round(mean + t_critical * se, 3))
Outputn: 300 | mean: 3.93 | s: 0.829
Standard error: 0.0479 | stats.sem: 0.0479
t critical: 1.968
95% interval: 3.836 - 4.024With the formula, the interval is 3.836 to 4.024. In lesson 30, the bootstrap with 10,000 repeats gave 3.837 to 4.020. The two ways end up almost in the same place, because both ask the same question: "How much would the mean move with another 300 customers?" The bootstrap answers it by trying thousands of times, and the formula answers it by using the central limit theorem from lesson 26. The advantage of the formula is its speed and the fact that it gives the same result every time. The advantage of simulation is that it also works for statistics that have no formula (like the median).
SciPy also gives the interval in a single line: stats.t.interval(0.95, n - 1, loc=x.mean(), scale=stats.sem(x)). It takes three inputs: the confidence level, the degrees of freedom, and loc (the center, which is the mean) with scale (the width unit, which is the standard error). The cell below calculates the same interval in three ways: by hand, with t.interval, and with the bootstrap from lesson 30. Then set the column variable to "recommend_score":
Try it now· not graded; doesn't affect progress
What does the interval say, and what does it not say? We talked about this in detail in lesson 30; the same holds for an interval built with a formula. Test yourself:
The 95% t interval for mean satisfaction is 3.84 to 4.02. The customer scores range from 2 to 5. Which sentence follows from this interval?
Now the manager's first question: "The target is 4. Do we reach it?" Let's write the hypotheses in the language of lessons 27 and 28. H₀: the mean satisfaction of all customers is 4. H₁: it is different from 4 (two-sided; the manager wants to know about being both below and above). The observed mean is 3.93.
In lesson 31, you defined the z statistic for a proportion as "how many standard errors is the observed value from the claim?" For a mean, the same distance is called the t statistic:
t = (mean − claim) / standard error = (3.93 − 4) / 0.0479 = −1.46
The mean is 1.46 standard errors below the target. How surprising is that? If H₀ is true, the t statistic follows a t distribution with 299 degrees of freedom; the two-sided p is the total area of the two tails at a distance of at least 1.46 in this distribution. First, follow t step by step:
Run the code line by line: see which line runs next, the variable boxes and the output.
mean = 3.93 s = 0.829 n = 300 claim = 4 se = s / n ** 0.5 t = (mean - claim) / se print("Standard error:", round(se, 4)) print("The mean is", round(abs(mean - claim), 2), "points below the target") print("t:", round(t, 2))
Let's do it with code, both by hand and with the ready-made SciPy test. stats.ttest_1samp(x, 4) ("one-sample t-test") takes the data and the claimed mean; the statistic field of the result gives t, the pvalue field gives the two-sided p, and the confidence_interval() method calculates the same interval:
import pandas as pd from scipy import stats x = pd.read_csv("survey.csv")["satisfaction"] n = len(x) t = (x.mean() - 4) / stats.sem(x) p_by_hand = 2 * stats.t.sf(abs(t), n - 1) print("By hand: t =", round(t, 2), "| p =", round(p_by_hand, 3)) result = stats.ttest_1samp(x, 4) ci = result.confidence_interval() print("ttest_1samp: t =", round(result.statistic, 2), "| p =", round(result.pvalue, 3)) print("95% interval:", round(ci.low, 3), "-", round(ci.high, 3))
OutputBy hand: t = -1.46 | p = 0.145
ttest_1samp: t = -1.46 | p = 0.145
95% interval: 3.836 - 4.024stats.t.sf(abs(t), n - 1) gives the area of the right tail, like norm.sf in lesson 26; because the test is two-sided, we multiplied by 2. Compare p = 0.145 with α = 0.05: p ≥ α, so we fail to reject H₀.
We can find this result with a simulation too. The idea is the same as in lesson 27: imitate the world as if H₀ were true. For this, we shift the data: we subtract 3.93 from every score and add 4, so we get an "H₀ world" with the same spread but a mean of exactly 4. From this shifted data, we draw bootstrap means as in lesson 30, and we count how many of them are at least 0.07 away from 4. We do not expect you to write this technique; the code is ready, so just compare the result:
Try it now· not graded; doesn't affect progress
The p from the simulation is 0.147, and from the formula it is 0.145. The two ways end up in the same place again.
Now what do we tell the manager? The most common mistake is to write this sentence: "p > 0.05, so satisfaction is exactly 4." Remember from lesson 28: failing to reject does not prove H₀. Look at the interval: 3.84 to 4.02. This interval contains 4, but it also contains 3.90 and 3.85. The data fit "mean 4", but they also fit "mean 3.85". The correct sentence is: "With this data, we could not show that the mean differs from the target."
Here the interval says more than the test. The test only says yes or no to the question "Does it fit 4?" The interval also answers the question "How far behind could we be in the worst case?": the lower end is 3.84, so we could be at most 0.16 points below the target. If the manager finds 0.16 points unimportant, they can relax; if they find it important, they will want to collect more data. The link between the test and the interval is the same as in lesson 30: in a two-sided test, p < 0.05 and the 95% interval leaving the claim outside are the same thing.
A report sentence is always built in the same order. Put the parts in order:
Put the sentences of the report paragraph for the manager in the right order: first the sample summary, then the interval, the test result, the decision, and finally the limitation.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The manager's second question compares two groups. In the survey, there are 130 customers whose orders were sent with Arrow Express and 80 customers whose orders were sent with Caravan Freight. The mean for Arrow Express is 4.19 and for Caravan Freight it is 3.66; the difference is 0.53 points. In lesson 29, you tested a difference like this by shuffling the labels. The pattern is the same with a formula:
t = (difference − 0) / standard error of the difference
The standard error of the difference is built from the standard errors of the two groups: √(s₁² / n₁ + s₂² / n₂). The movements of two separate means add up, so the difference moves more than a single mean. You do not need to do the calculation by hand: stats.ttest_ind(x, y, equal_var=False) ("independent", two independent groups) gives t and p, and confidence_interval() gives the interval of the difference. The difference is always calculated as the first group minus the second group.
What does equal_var=False mean? An older version of the test (the Student t-test) assumes that the spreads of the two groups are equal. In real data, both the sizes (130 and 80) and the spreads of the groups can be different; equal_var=False chooses the Welch t-test, which does not make this assumption. If the groups really have equal spreads, Welch gives almost the same result; if not, the Student test can mislead. This is why Welch is the safe default, and we will always use it in this course. In SciPy, if you do not write equal_var, the default is True, which is the Student test; so never forget this parameter.
Compare Arrow Express and Caravan Freight (Example 2). Then set the g1 variable to "Gull Post" and compare Gull Post with Caravan Freight (Example 3):
Try it now· not graded; doesn't affect progress
Between Arrow Express and Caravan Freight, the difference is 0.53 points; Welch t = 4.47, p = 0.000015 (Python writes this as 1.5e-05: 1.5 × 10⁻⁵). The 95% interval for the difference is 0.296 to 0.764. The whole interval is above zero: Arrow Express customers seem to be happier by at least 0.3 and at most 0.76 points.
Let's ask the same question with the permutation test from lesson 29. If H₀ "the carrier does not affect satisfaction" is true, shuffling the carrier labels among the 210 customers should change nothing:
import numpy as np import pandas as pd a = pd.read_csv("survey.csv") two = a[a["carrier"].isin(["Arrow Express", "Caravan Freight"])] group = two["carrier"].to_numpy() score = two["satisfaction"].to_numpy() observed = score[group == "Arrow Express"].mean() - score[group == "Caravan Freight"].mean() rng = np.random.default_rng(42) diffs = [] for i in range(10_000): shuffled = rng.permutation(group) diffs.append(score[shuffled == "Arrow Express"].mean() - score[shuffled == "Caravan Freight"].mean()) diffs = np.array(diffs) print("Observed difference:", round(observed, 3)) print("Largest shuffled difference:", round(np.abs(diffs).max(), 3)) print("Shuffles as extreme as observed:", (np.abs(diffs) >= abs(observed)).sum(), "/ 10000")
OutputObserved difference: 0.53
Largest shuffled difference: 0.48
Shuffles as extreme as observed: 0 / 10000None of the 10,000 shuffles reached 0.53; the most extreme one stayed at 0.48. It would not be right to write the p from the simulation as 0: it only means we did not see it even once in 10,000 tries. The correct way to write it is "p < 1/10,000", which is p < 0.0001. The 0.000015 from the formula fits this limit. The formula can give a number for p values too small for the simulation to measure; this is also an advantage of the formula.
For Gull Post and Caravan Freight, the situation is different: the difference is 0.126 points, p = 0.31, and the interval is −0.118 to 0.371. The interval contains zero.
The 95% interval for the Gull Post − Caravan Freight satisfaction difference is −0.12 to 0.37 (p = 0.31). Which sentence do you write to the manager?
Formulas are faster than simulation, but they have assumptions behind them. In a simulation, you can see these assumptions yourself; in a formula, you cannot, so you check them yourself before the test. There are three conditions:
1. Independent observations. Each observation must come from a separate unit: the same customer must not be counted twice, and someone in one group must not affect someone in the other group. Two measurements of the same unit (the revenue of the same 40 products in two periods, the before and after scores of the same student) are not two independent groups; they are paired data and need another method (you will see it briefly in lesson 35). If you apply ttest_ind to this kind of data, you ignore the link between the two measurements.
2. A random sample or random assignment. The principle from lesson 3: a result generalizes to the population only if the sample represents the population, and you can call a difference between two groups a cause only if the groups were formed randomly. Arrow Express and Caravan Freight customers were not assigned randomly; they may work in different cities and with different products. The formula does not fix this problem.
3. Enough n, or data that is not extremely skewed. The t formula assumes that the sample mean is distributed close to the normal model. The central limit theorem from lesson 26 provides this with a large n; with a small n, it is not provided if the data is very skewed.
Let's see the two sides of the third condition in the case. Order amounts are strongly right-skewed: the skewness is 4.18 (lesson 16). Is the mean amount of mobile and desktop orders different (Example 4)?
import pandas as pd from scipy import stats s = pd.read_csv("orders.csv") mobile = s.loc[s["device"] == "mobile", "amount"] desktop = s.loc[s["device"] == "desktop", "amount"] print("Skewness:", round(s["amount"].skew(), 2)) print("Mobile:", len(mobile), "| mean:", round(mobile.mean(), 2), "| median:", round(mobile.median(), 2)) print("Desktop:", len(desktop), "| mean:", round(desktop.mean(), 2), "| median:", round(desktop.median(), 2)) result = stats.ttest_ind(mobile, desktop, equal_var=False) ci = result.confidence_interval() print("Difference:", round(mobile.mean() - desktop.mean(), 2), "| p:", round(result.pvalue, 3)) print("95% interval:", round(ci.low, 2), "-", round(ci.high, 2))
OutputSkewness: 4.18
Mobile: 516 | mean: 68.83 | median: 44.9
Desktop: 369 | mean: 84.9 | median: 44.95
Difference: -16.07 | p: 0.024
95% interval: -30.06 - -2.09The n is large (516 and 369), so the formula works for means despite the skewness: the mean amount of mobile orders is lower than desktop by $2.09 to $30.06. But look at the medians: $44.90 and $44.95. A typical mobile order and a typical desktop order have the same amount; the difference between the means comes from a few very large desktop orders. Here is a common misunderstanding: "The t-test was significant, so the typical customer spends differently." No: the t-test tests the mean. In skewed data, the mean does not represent the typical value (lesson 12). If your question is "Who contributes more to total revenue?", t answers the right question; if your question is "Is the typical order different?", it answers the wrong one. You will see an option based on ranks in lesson 35.
Now think of the same skewed data with a small sample: only the first 10 orders (Example 5).
import pandas as pd from scipy import stats s = pd.read_csv("orders.csv") first10 = s["amount"].head(10) print(first10.tolist()) print("Mean:", round(first10.mean(), 2), "| median:", round(first10.median(), 2)) low, high = stats.t.interval(0.95, 9, loc=first10.mean(), scale=stats.sem(first10)) print("95% t interval:", round(low, 2), "-", round(high, 2))
Output[249.9, 74.95, 164.95, 15.95, 44.95, 719.92, 64.95, 29.95, 34.95, 12.9]
Mean: 141.34 | median: 54.95
95% t interval: -13.67 - 296.35The lower end of the interval is minus $13.67. An order cannot have a negative amount; the formula stretches the interval equally on both sides of the mean because it assumes a symmetric normal model. One order of $719.92 among ten inflates both the mean and the standard deviation. This also refutes a misunderstanding: "With a small sample, t is always safe, because Gosset found it for small samples anyway." Gosset's t is reliable in a small sample only if the data are roughly symmetric. When 10 observations and extreme skewness come together, the condition fails. What do you do? Collect more data, report the median instead of the mean, or at least mark the interval as "not reliable".
Match the four situations with the right way:
What should be done in each situation?
For each row, pick its match from the list, then check.
The same pattern works in every field (Example 6). In two shops of a coffee chain, the preparation time (in minutes) of 12 orders each was measured during one day. Shop A tells customers "your coffee is ready in 4 minutes".
from scipy import stats a = [4.1, 4.8, 4.4, 4.2, 4.3, 3.5, 5.1, 3.6, 4.8, 4.3, 4.8, 4.8] b = [5.7, 4.6, 5.0, 4.7, 5.1, 5.3, 5.1, 5.8, 5.5, 5.9, 6.2, 4.5] result = stats.ttest_ind(a, b, equal_var=False) ci = result.confidence_interval() print("A mean:", round(sum(a) / len(a), 2), "| B mean:", round(sum(b) / len(b), 2)) print("Welch t:", round(result.statistic, 2), "| p:", round(result.pvalue, 4)) print("Difference (A - B) interval:", round(ci.low, 2), "-", round(ci.high, 2)) claim = stats.ttest_1samp(a, 4) ci4 = claim.confidence_interval() print("A vs 4 minutes: t =", round(claim.statistic, 2), "| p =", round(claim.pvalue, 3)) print("A mean interval:", round(ci4.low, 2), "-", round(ci4.high, 2))
OutputA mean: 4.39 | B mean: 5.28
Welch t: -4.18 | p: 0.0004
Difference (A - B) interval: -1.33 - -0.45
A vs 4 minutes: t = 2.72 | p = 0.02
A mean interval: 4.08 - 4.71ttest_ind and ttest_1samp also work with a plain Python list instead of a pandas column. The results: A is faster than B by 0.89 minutes on average (interval 0.45 to 1.33 minutes). A's promise of "4 minutes" does not fit the data well: its mean is 4.39, and the interval 4.08 to 4.71 leaves 4 outside (p = 0.02). There are 12 observations in each group, but the times are roughly symmetric and there are no extreme values, so the conditions look reasonable. The real question is how these 24 orders were chosen.
The chain's manager sees the results: shop B is slower by 0.89 minutes on average (interval 0.45 to 1.33 minutes, p = 0.0004). "Let's close B," they say. What do you suggest?
Pick an option and see what happens. There are no points; you can try the other options too.
In lessons 31 and 32, you used the same pattern in three places:
| What is estimated | Standard error | Critical value | SciPy |
|---|---|---|---|
| A proportion (31) | √(p(1 − p) / n) | normal (1.96) | by hand |
| A single mean | s / √n | t, n − 1 degrees of freedom | ttest_1samp, t.interval |
| A difference of two means | √(s₁² / n₁ + s₂² / n₂) | t (Welch) | ttest_ind(..., equal_var=False) |
In each of them, the interval is "estimate ± critical value × standard error", and the test statistic is "(estimate − claim) / standard error". The simulation reaches the same numbers; the formula is only a shortcut.
One question stays open: the p between Arrow Express and Caravan Freight is as small as 0.000015. Does this mean the difference is large? The difference is 0.53 points; on a scale from 1 to 5, is that a lot or a little? In lesson 33, you will see how not to confuse the smallness of a p-value with the importance of a difference, and you will see the two types of error.
OutputDelivered: 851 | mean: 2.981
t: -0.47 | p: 0.636
95% interval: 2.903 - 3.059The mean is 2.98 days, and the interval is 2.90 to 3.06 days; 3 is inside the interval, and p = 0.64. The promise of "3 days on average" fits the data. dropna() leaves out the empty delivery times of orders that were not delivered (returned or canceled); otherwise ttest_1samp would return nan as the result.
Tip
Before you print a p-value, ask yourself: does it become 0 when rounded? If it does, write "p < 0.001". The same is true in a simulation: if none of the 10,000 tries is as extreme as the observed value, write "p < 1/10,000", not "p = 0".