Parametric Tests
local graph
Chapter 4 — Parametric Tests
Section titled “Chapter 4 — Parametric Tests”In the previous chapter, we introduced the concept of a hypothesis test and showed several applications of the z-test. The z-test is a type of hypothesis test in a family of hypothesis tests called parametric tests. Parametric tests are powerful hypothesis tests, but the application of parametric tests requires certain assumptions to be met by the data. While the z-test is a useful test, it is limited by the required assumptions. In this chapter, we will discuss several more parametric tests, which will expand our parametric tool set. More specifically, we will discuss the various applications of the t-test, how to perform tests when more than two subgroups of data are present, and the hypothesis test for Pearson’s correlation coefficient. We will complete the chapter with a discussion on power analysis for parametric tests.
In this chapter, we’re going to cover the following main topics:
- Assumptions of parametric tests
- T-test —a parametric hypothesis test
- Tests with more than two groups and analysis of variance (ANOVA)
- Pearson’s correlation coefficient
- Power analysis examples
Assumptions of parametric tests
Section titled “Assumptions of parametric tests”Parametric tests make assumptions about population data that require the statistics practitioner to perform analysis of data prior to modeling, especially when using sample data because the sample statistics are leveraged as estimates for the population parameters when the true population parameters are unknown. These are the three primary assumptions of parametric hypothesis tests:
- Normally distributed population data
- Samples are independent
- Equal population variances (when comparing two or more groups)
In this chapter, we discuss the z-test, t-test, ANOVA, and Pearson’s correlation. These tests are used on continuous data. In addition to these assumptions, Pearson’s correlation requires data to contain paired samples. In other words, there must be an equal number of samples in each group being compared as Pearson’s correlation is based on pairwise comparisons.
While these assumptions are ideal, there are many occasions where these cannot be ensured. Consequently, it is useful to understand there is some robustness to these assumptions, depending on the test.
Normally distributed population data
Section titled “Normally distributed population data”Because in parametric hypothesis tests we are interested in gaining inferences about population parameters, such as the mean or standard deviation, we must assume the parameter of choice is representative of the distribution and that it is safe to assume a central tendency in the data. We must also assume the statistic (parametric value taken from a sample or sampling distribution) is representative of its respective population parameter. Therefore, since we assume in parametric hypothesis tests that the population is normally distributed, the sample should also be normally distributed as well. Otherwise, it is not safe to assume the sample is representative of the population.
Parametric hypothesis tests rely heavily on the mean and assume it is strongly representative of the data’s central point (all population data is centrally distributed around the mean). Consider where the means of two distributions are being compared to test if there is a statistically significant difference between them. If the distributions are skewed, the mean will not be the center point of the data and, consequently, cannot represent the distributions very well. Since this would be the case, inference obtained from a test comparing the means would not be reliable.
Robustness to normally distributed data
Section titled “Robustness to normally distributed data”Many hypothesis tests specify degrees of freedom when using samples to make estimates about populations. Degrees of freedom force models to assume there is extra variance in the distributions used than actually present. While the statistical parameters in the analysis remain the same, the assumed extra variance forces measures of central tendency closer. Stated differently, using degrees of freedom forces measures of central tendency to be more centrally representative of the distributions from which they are calculated. The reason for this is that it is assumed samples—while representative of their overall populations—represent their populations with a margin of error. Consequently, parametric hypothesis tests using degrees of freedom have some robustness to violations of the requirement for normally distributed data.
In the plots shown in Figure 4*.1*, we have a slightly skewed distribution. One applies degrees of freedom while the other does not. We can see the mean and median have the same distance between them whether degrees of freedom are used or not. However, the distribution using degrees of freedom takes on more errors (more variance):

Figure 4.1 – Visualizing the influence of degrees of freedom
When using a hypothesis test that considers the mean, we can see that the mean, while not centered (as is the median), approximates the center of the distribution much more closely, relative to all data points, when degrees of freedom are used. Since parametric hypothesis tests use the mean as the central point, this is important for the usefulness of the model as the mean is more representative of the central point of the data when degrees of freedom are used. This is a primary reason there is some robustness to normality. Some other robustness is in the statistical interpretation, such as in choosing the level of confidence; if a distribution is not perfectly normally distributed, it may be beneficial to use a 90% level of confidence rather than a 99% level of confidence, for example.
Testing for normally distributed data
Section titled “Testing for normally distributed data”There are multiple methods for determining whether a distribution is normally distributed and thus can be used in parametric hypothesis testing. Generally, the level of adherence to normality is up to the discretion of the researcher. The methods in this section leave some margin for debate on normality based on visual inspection as well as levels of statistical significance applied.
Visual inspection
Section titled “Visual inspection”The best tests to identify whether a distribution is normally distributed or not are based on visual inspection. We can use Quantile-Quantile (QQ) plots and histograms—among other tests—to visually inspect the distributions.
In the following code snippet, we generate plots of the original data as well as the QQ plots using the scipy.stats module’s probplot function:
import matplotlib.pyplot as pltimport scipy.stats as statsimport numpy as npmu, sigma = 0, 1.1normally_distributed = np.random.normal(mu, sigma, 1000)In Figure 4*.2*, we can see in the first column a histogram of exponentially distributed data and, beneath it, its QQ plot. As the points are very far from approximating adherence to the 45-degree red line, which represents a pure normal distribution, we can conclude the data is not normally distributed. By visually inspecting the data in the second column, we can see the histogram exhibits an approximately normally distributed dataset. This is backed up by the QQ plot below it, where the points mostly approximate the 45-degree red line. With respect to the tails of the QQ plot, these data points represent the density of skewness. We expect with a normally distributed dataset that the bulk of data points will tend toward the center of the red line. With the exponential distribution, we can see a heavy density toward the left, lower tail of the red line, and a sparse scattering of points toward the upper-right side of the line. The QQ plot can be read left to right, mirroring the spread seen in the histogram, where the smallest values appear on the left-hand side of the x axis and the largest on the right-hand side:

Figure 4.2 – Visually assessing normality with QQ and histogram plots
Visual inspection of the QQ plots and histograms should be enough to help a researcher conclude whether the normality assumption has been violated or not. However, in cases where one might not want to perform visual inspection—such as when constructing a data science pipeline—there are alternative approaches that provide specific measurements of normality. Three of the most commonly used tests are the Kolmogorov-Smirnov, Anderson-Darling, and Shapiro-Wilk tests.
The Kolmogorov-Smirnov test focuses more on the centrality of the data. Consequently, however, the test has less power if there is a wide variance around the center of the data. Anderson-Darling focuses more on the tails of the data than the center and is more likely to identify non-conformity to normality if data is heavy-tailed with extreme outliers. These two tests perform well on large sample sizes but do not have as much power when sample sizes are lower. The third test we consider, Shapiro-Wilk, is more general than the Kolmogorov-Smirnov and Anderson-Darling tests and therefore more robust to small sample sizes. Based on these traits, it may be more useful to use Shapiro-Wilk tests in an automated pipeline. Alternatively, it may be better to lower the level of confidence for the test being applied.
Kolmogorov-Smirnov
Section titled “Kolmogorov-Smirnov”The Kolmogorov-Smirnov test can be used to test the null hypothesis that a given sample distribution is normally distributed. This version of the Kolmogorov-Smirnov test is the one-sample goodness-of-fit test, which performs analysis against a benchmark cumulative density distribution. When running the kstest function in the scipy.stats module, using stats.norm.cdf (scipy ’s cumulative density function) performs this one-sample version of the test. The two-sample version tests against a specified distribution to determine whether the two distributions match. In the two-sample case, the distribution to be tested must be provided as a numpy array instead of the stats.norm.cdf function used in the code snippet shown below Figure 4*.3*. However, this is outside of the scope of testing for normality, so we will not look at this.
Kolmogorov-Smirnov measures a calculated test statistic against a table-based critical value (kstest calculates this internally). As with other hypothesis tests, if the test statistic is larger than the critical value, the null hypothesis that the given distribution is normally distributed can be rejected. This can also be assessed if the p-value is low enough to be significant. The test statistic is calculated as the absolute value of the maximum distance between all data points in the given distribution against the cumulative density function.
Kolmogorov-Smirnov special requirement
The Kolmogorov-Smirnov test requires data to be centered around zero and scaled to a standard deviation of one. All data must be transformed for the test, but inference can be applied to the pre-transformed distribution; the centered and scaled distribution does not need to be the distribution used in further statistical testing or analysis.
In the following code snippet, we test to confirm whether a normally distributed dataset, normally_distributed, is normally distributed. The dataset has a mean of 0 and a standard deviation of 1. The output confirms the data is normally distributed. The plots in Figure 4*.3* show the normally distributed distribution centered around a mean of 0 with a standard deviation of 1, and on the right of it is the exponentially transformed version of the same distribution:
from scipy import statsimport numpy as npmu, sigma = 0, 1normally_distributed = np.random.normal(mu, sigma, 1000)
Figure 4.3 – Normally distributed and exponential data
Here, we run the Kolmogorov-Smirnov test:
stats.kstest(normally_distributed, stats.norm.cdf)The statsmodels Kolmorogov-Smirnov test yielded the following results for our data:
KstestResult(statistic=0.0191570377833315, pvalue=0.849436919292824)
If we use the same data, but transform it exponentially to be right-skewed, the same test indicates the data is no longer normally distributed:
stats.kstest(np.exp(normally_distributed), stats.norm.cdf)The signficant p-value confirms non-normality:
KstestResult(statistic=0.5375205782404135, pvalue=9.59979841227121e-271)
Next, let us take a distribution of 1,000 samples with a mean of 100 and a standard deviation of 2. We need to center it to a mean of 0 with unit variance (standard deviation of 1). In the following code snippet, we generate the data, then perform the scaling and save it to the normally_distributed_scaled variable:
mu, sigma = 100, 2normally_distributed = np.random.normal(mu, sigma, 1000)normally_distributed_scaled = ( normally_distributed-normally_distributed.mean()) / normally_distributed.std()Now that the data is centered and scaled as required, we check it using the Kolmogorov-Smirnov test. As expected, the data is confirmed normally distributed:
stats.kstest(normally_distributed_scaled, stats.norm.cdf)This is the output:
KstestResult(statistic=0.02597307287070466, pvalue=0.5016041053535877)
Anderson-Darling
Section titled “Anderson-Darling”Similar to the Kolmogorov-Smirnov test, the Anderson-Darling test measures a given distribution against a normally distributed distribution. In scipy ’s anderson test, we can test against other distributions, but the default argument specifying a normal distribution, dist="norm", assumes a null hypothesis that the given distribution is statistically the same as a normally distributed distribution. For each distribution tested against, a different set of critical values must be calculated.
Anderson-Darling compared to Kolmogorov-Smirnov
Note that while both the Anderson-Darling and Kolmogorov-Smirnov tests use the cumulative density frequency distributions to test for normality, the Anderson-Darling test is different from the Kolmogorov-Smirnov test because it weights the variance in the tails of the cumulative density frequency distribution more than the middle. This is because the variance in the tails can be measured in smaller increments than in the middle of the distribution. Consequently, the Anderson-Darling test is more sensitive to tails than the Kolmogorov-Smirnov test. In line with the Kolmogorov-Smirnov test, a test statistic is calculated and measured against a critical value. If the test statistic is larger than the critical value, the null hypothesis that the given distribution is normally distributed can be rejected at the specified level of significance.
Here, we are using the Anderson-Darling test to test a random normal probability distribution generated with a mean of 19 and a standard deviation of 1.7. We also test an exponentially transformed version of this data:
import matplotlib.pyplot as pltimport seaborn as snsimport numpy as npmu, sigma = 19, 1.7normally_distributed = np.random.normal(mu, sigma, 1000)not_normally_distributed = np.exp(normally_distributed);Figure 4*.4* shows plots of the data:

Figure 4.4 – Normal distribution versus heavy-tailed exponential distribution
In the code and output shown next, in Figure 4*.5*, we can see the distribution is normally distributed at all levels of significance. Recall that the level of significance is the p-value (that is, a level of significance = 15.0 means a p-value of 0.15 or smaller is significant):
from scipy import statsimport pandas as pdimport numpy as npdef anderson_test(data): data = np.array(data) test_statistic, critical_values, significance_levels = stats.anderson(normally_distributed, dist='norm') df_anderson = pd.DataFrame({'Test Statistic':np.repeat(test_statistic, len(critical_values)), 'Critical Value':critical_values, 'Significance Level': significance_levels}) df_anderson.loc[df_anderson['Test Statistic'] >= df_anderson['Critical Value'], 'Normally Distributed'] = 'No' df_anderson.loc[df_anderson['Test Statistic'] <df_anderson['Critical Value'], 'Normally Distributed'] = 'Yes' return df_anderson;mu, sigma = 19, 1.7normally_distributed = np.random.normal(mu, sigma, 1000)anderson_test(normally_distributed)Here, the data generated through the numpy random.normal function is tested with the Anderson-Darling method and confirmed to be normally distributed:
| Test statistic | Critical value | Significance level | Normally distributed |
|---|---|---|---|
| 0.191482344 | 0.574 | 15 | Yes |
| 0.191482344 | 0.653 | 10 | Yes |
| 0.191482344 | 0.784 | 5 | Yes |
| 0.191482344 | 0.914 | 2.5 | Yes |
| 0.191482344 | 1.088 | 1 | Yes |
Figure 4.5 – Anderson-Darling results for normally distributed data
Here, we test an exponential transformation of the normally distributed data to check for normality. The data is exponentially distributed and should reject at all levels of significance. However, we see in Figure 4*.6* that it has failed to reject at the 0.01 level of significance (99% confidence). Therefore, depending on the use case, it may be prudent to check all levels of significance, use a different test, or make a decision based on multiple tests:
not_normally_distributed = np.exp(normally_distributed)anderson_test(not_normally_distributed)Our Anderson-Darling test of non-normally distributed data outputs are as follows in Figure 4*.6*:
| Test statistic | Critical value | Significance level | Normally distributed |
|---|---|---|---|
| 0.96277351 | 0.574 | 15 | No |
| 0.96277351 | 0.653 | 10 | No |
| 0.96277351 | 0.784 | 5 | No |
| 0.96277351 | 0.914 | 2.5 | No |
| 0.96277351 | 1.088 | 1 | Yes |
Figure 4.6 – Anderson-Darling results for non-normally distributed data
Shapiro-Wilk
Section titled “Shapiro-Wilk”The Shapiro-Wilk test is a goodness-of-fit test that checks whether a given distribution is normally distributed. The test checks how closely a distribution of observed values centered on 0 and scaled to a unit variance of 1 approximates an observed centered and scaled standard normal distribution. This centering and scaling (called standardizing) are performed within the function in the scipy.stats shapiro module, so input data does not need to be altered prior to testing. The level of significance for this test in scipy is 0.05.
Shapiro-Wilk compared to Kolmogorov-Smirnov and Anderson-Darling
Shapiro-Wilk is ideal, compared to Kolmogorov-Smirnov and Anderson-Darling, for testing small sample sizes of roughly less than 50. However, one drawback is that since Shapiro-Wilk uses repeated sampling and testing for the calculated test statistic by applying Monte Carlo simulation, the law of large numbers poses a risk that as the sample size increases, there is an inherent increase in the risk of encountering a type II error (a loss of power) and failing to reject the null hypothesis, where the null hypothesis states the given distribution is normally distributed.
Using the same distributions as in the Anderson-Darling test, we test with Shapiro-Wilk. We can see with the random normal distribution with a mean of 19 and a standard deviation of 1.7, the Shapiro-Wilk test has confirmed with a p-value of 0.99 that the null hypothesis that the input distribution is normally distributed should not be rejected:
mu, sigma = 19, 1.7normally_distributed = np.random.normal(mu, sigma, 1000)stats.shapiro(normally_distributed)This is the output:
ShapiroResult(statistic=0.9993802905082703, pvalue=0.9900037050247192)
When testing using the exponentially transformed version of the normally distributed data, we find a significant p-value (p = 0.0), indicating we have enough evidence to reject the null hypothesis and conclude the distribution is not normally distributed:
not_normally_distributed = np.exp(normally_distributed)stats.shapiro(not_normally_distributed)This is the output:
ShapiroResult(statistic=0.37320804595947266, pvalue=0.0)
Independent samples
Section titled “Independent samples”In parametric hypothesis testing, the independence of samples is another important assumption. Two effects can occur from non-independent sampling. One effect occurs when subgroup sampling is performed. The issue here is that responses in one subgroup of the population may be different than responses from another subgroup of the same population or even more similar to those of a different population. However, when sampling representative of the overall population is taken, this type of subgroup difference may not be very representative of the population.
Another effect of non-independent sampling is when samples are taken close enough together in time that the occurrence of one precludes or excludes the occurrence of another. This is called serial (or auto-) correlation.
Parametric tests are not typically robust to violations of this requirement as it has direct, categorical implications on the interpretability of test outcomes. With respect to subgroup sampling, this can be prevented through a well-structured sampling approach such as those outlined in Chapter 1*, Sampling and Generalization*. However, as regards the serial effect, we can test for autoregressive correlation (also called serial correlation) in the data.
Durbin-Watson
Section titled “Durbin-Watson”One of the most common tests performed to assess a lack of independence in sampling is the first-order (also referred to as lag-one) autoregressive test called the Durbin-Watson test. Autoregressive means previous data points are used to predict the current data point. First-order means the last sampled data point (lag one) is the point most significantly correlated to the most recently sampled data point (lag zero) in a sequence of sampled data. In first-order autocorrelation, the correlation for each data point is strongest with the previous data point. The Durbin-Watson test does not test whether any value is correlated to the value before it, but instead if, overall, there is a strong enough relationship between each value and the value before it to conclude there is significant autocorrelation. In that sense, there is some robustness to non-independent sampling such that an accident or two may not completely invalidate a hypothesis test, but a consistent recurrence of this type of violation will.
A Durbin-Watson value of 2 indicates no significant autocorrelation, a value between 0 and 2 represents positive (direct) autocorrelation, and a value between 2 and 4 represents negative (inverse) autocorrelation.
In the following example, we have two distributions, each with 1,000 samples. The distribution on the left is a sinusoidal distribution that exhibits strong autoregressive correlation, and the distribution on the right is a set of randomly generated data displaying as white-noise variance (random points centered around a mean of 0). Using the durbin_watson() function from the statsmodels.stats module, we are able to confirm direct, positive lag-one autocorrelation in the sinusoidal pattern (a very small Durbin-Watson value) and a Durbin-Watson statistic of 2.1 with the random noise, indicating no autocorrelation. Therefore, in Figure 4*.7*, the plot on the left is not composed of independent samples whereas the plot on the right is:
from statsmodels.stats.stattools import durbin_watsonimport matplotlib.pyplot as pltimport numpy as npmu, sigma = 0, 1.1independent_samples = np.random.normal(mu, sigma, 1000)correlated_samples = np.linspace(-np.pi, np.pi, num=1000)fig, ax = plt.subplots(1,2, figsize=(10,5))ax[0].plot(correlated_samples, np.sin(correlated_samples))ax[0].set_title('Durbin Watson = {}'.format( durbin_watson(correlated_samples)))ax[1].plot(independent_samples)ax[1].set_title('Durbin Watson = {}'.format( durbin_watson(independent_samples)))
Figure 4.7 – Serially correlated and normally distributed sequence data
Equal population variance
Section titled “Equal population variance”Similar to the assumption of normally distributed data, the assumption of equal population variance—also referred to as homogeneity of variance—is about the shape of the physical properties of the distributions being compared. Assuming equal population variance helps increase the power of a parametric test. This is because there is confidence when means are identified as being different; we also know the degree of potential distribution overlap. When a test has an intuition about the location of the full distributions—in effect, true knowledge of the effect size—power increases. Conversely, as variances diverge, power decreases.
Robustness to equal population variance
Section titled “Robustness to equal population variance”While equal population variance is useful in parametric testing, modifications to these tests exist that help results be robust to deviance from equal variance. One prominent modified version of these tests uses the Welch-Satterthwaite adjustment to the degrees of freedom used. Because applying the same degree of freedom to each group when each group has a different variance would result in a misrepresentation of the data, the Welch-Satterthwaite adjustment accounts for variance differences when allocating degrees of freedom to parametric tests that assume equal variance. Two common tests that use the Welch-Satterthwaite adjustment are Welch’s t-test and Welch’s ANOVA test. When used on small samples, these tests may not be reliable, but when used on sample sizes large enough to have sufficient power, the results should be approximately the same as their non-Welch counterparts.
Testing for equal variance
Section titled “Testing for equal variance”When testing for equal variance among distributions, we have two prominent tests: Levene’s test for equality of variances and Fisher’s F-test.
Levene’s test for equality of variances
Section titled “Levene’s test for equality of variances”Levene’s test for equality of variances is useful when testing for homogeneity of variance of two or more groups. In the code snippet shown below Figure 4*.8*, we test with three distributions, each having a sample size of 100, a mean of 0, and standard deviations of 0.9, 1.1, and 2. Figure 4*.8* is a plot of the three distributions generated using the data output from the code above Figure 4*.8*.
from scipy.stats import levenenp.random.seed(26)mu1, sigma1, mu2, sigma2, mu3, sigma3 = 0,0.9,0,1.1,0,2distro1, distro2, distro3 = pd.DataFrame(), pd.DataFrame(), pd.DataFrame()distro1['x'] = np.random.normal(mu1, sigma1, 100)distro2['x'] = np.random.normal(mu2, sigma2, 100)distro3['x'] = np.random.normal(mu3, sigma3, 100)We can see how their different standard deviations impact their range.

Figure 4.8 – Distributions for multiple equality of variance testing
We can see the test is sensitive to violations of non-homogenous variance because the result of this is a statistically significant p-value indicating non-homogenous variance:
f_statistic, p_value = levene(distro1['x'], distro2['x'], distro3['x'])if p_value <= 0.05: print('The distributions do not have homogenous variance. P-value = %.4f, F-statistic = %.4f'%(p_value, f_statistic))else: print('The distributions have homogenous variance.P-value = %.4f, F-statistic = %.4f'%(p_value, f_statistic))This is the output:
The distributions do not have homogenous variance. P-value = 0.0000
Fisher’s F-test
Section titled “Fisher’s F-test”Fisher’s F-test is useful when testing for homogeneity of variance for two groups at a time. This test compares a test statistic to a critical value to determine whether the variances are statistically the same or not. The calculated F-statistic is the variance of group one divided by the variance of group two. Group one is always the group with the larger variance. Using the preceding data, let us compare distribution 1 with distribution 3. Distribution 3 has a larger variance of 2, so that group’s variance will be the numerator when calculating the F-statistic. Since each group has a sample size of 100, their degrees of freedom for the table lookup will each be 99. However, since we will use the scipy Python package to compute the test, here, the table lookup is not needed as scipy does this for us with the f.cdf() function. In line with the results of the Levene test, the F-test indicates distribution 1 and distribution 3 do not have homogenous variance:
from scipy.stats import fdef f_test(inputA, inputB): group1 = np.array(inputA) group2 = np.array(inputB) if np.var(group1) > np.var(group2): f_statistic = np.var(group1) / np.var(group2) numeratorDegreesOfFreedom = group1.shape[0] - 1 denominatorDegreesOfFreedom = group2.shape[0] - 1 else: f_statistic = np.var(group2)/np.var(group1) numeratorDegreesOfFreedom = group2.shape[0] - 1 denominatorDegreesOfFreedom = group1.shape[0] - 1 p_value = 1 - f.cdf(f_statistic,numeratorDegreesOfFreedom, denominatorDegreesOfFreedom) if p_value <= 0.05: print('The distributions do not have homogenous variance. P-value = %.4f, F-statistic = %.4f'%(p_value, f_statistic)) else: print('The distributions have homogenous variance. P-value = %.4f, F-statistic = %.4f'%(p_value, f_statistic))f_test(distro3['x'], distro1['x'])This F-test output is as follows:
The distributions do not have homogenous variance. P-value = 0.0000, F-statistic = 102622.9745
T-test – a parametric hypothesis test
Section titled “T-test – a parametric hypothesis test”In the last chapter, the z-test for means was applied when population standard deviations were known. However, in the real world, it is not easy (or virtually impossible) to obtain the population standard deviation. In this section, we will discuss another hypothesis test called the t-test, which is used when the population standard deviations are unknown. The mean and the standard deviation of a population are estimated by taking the mean and the standard deviation of sample data representative of this population.
Broadly speaking, the method for the t-test for means is very similar to the one for the z-test for means, but the calculations for the test statistic and p-value are not the same as for the z-test. The test statistic is computed by the following formula:
Here,,, and are the sample mean, population mean, sample standard deviation, and sample size, respectively, which has a -distribution when the sample data,, is normally distributed. The following code illustrates the standard normal distribution (blue curve) with 1,000 samples and t-distribution (green and red curves) with two sample sizes—3 and 16 samples:
# librariesimport numpy as npimport scipy.stats as stats# creating normal distributionx =np.linspace(-5, 5, 1000) #create 1000 point from -5 to 5y = stats.norm.pdf(x) # create probability density for each point x - normal distribution# creating Student t distributions for 2 sample sizes n =3 and n =15degree_freedom1 = 2t_dis1 = stats.t.pdf(x, degree_freedom1)degree_freedom2 = 15t_dis2 = stats.t.pdf(x, degree_freedom2)The following visuallization is for these 3 distributions considered.

Figure 4.9 – Normal and t-distributions
Observe that the three curves have similar symmetry and shapes but there is more variability (or, in other words, heavier tails) for a sample with a smaller size. Historically, researchers considered a sample standard deviation to represent the population when the sample size was greater than 30, that is, the red curve approximates the blue curve when. It was also common to use the z-test if the sample distribution overlapped the standard normal distribution. This practice has some reasoning behind it because, previously, critical value tables were stored up to a sample size of 50, but nowadays, with the power of computation and the internet, the t values can be obtained easily with any sample size.
T-test for means
Section titled “T-test for means”One-sample and two-sample t-tests related to a population mean or means of two populations where the population variances or population standard deviations are unknown will be considered in this part.
To perform a t-test, the following assumptions need to be satisfied:
Normality: The sample is normally distributed
Independence: Observations are randomly selected from a population to form a sample or, in other words, they are independent
Let us consider the one-sample t-test in the following section.
One-sample t-test
Section titled “One-sample t-test”Similar to the one-sample z-test, the null and alternative hypotheses need to be considered in order to perform the hypothesis test. Three null and alternative hypotheses corresponding to left-tailed, right-tailed, and two-tailed t-tests are presented as follows:
Next, the level of significance,, needs to be specified following the research purpose. There are two approaches: the p-value approach and the critical value approach. In the p-value approach, the rejection rule (reject —the null hypothesis) is when the p-value is less than or equal to the specified level of significance chosen. In the critical value approach, the rejection rule is when the test statistic is less than or equal to the critical value for the left-tailed t-test, the test statistic is greater than or equal to for a right-tailed t-test, and the test statistic is less than or equal to or greater than or equal to for a two-tailed test. The last step is to interpret the statistical conclusion for the hypothesis test.
To find the p-value based on the value of the student distribution, we can use the following syntax:
scipy.stats.t.sf(abs(x), df)Here, x is the test statistic and df is the degree of freedom (df = n-1 where n is the sample size) in the formula.
For example, to find the p-value associated with a t-score of 1.9 with the degree of freedom 14 in a left-tailed test, this would be the Python implementation:
import scipy.statsround(scipy.stats.t.sf(abs(1.9), df=14),4)The output would be 0.0391. If the level of significance, then we reject the null hypothesis because the p-value is less than For a right-tailed t-test, similar Python code as in the left-tailed t-test is implemented to find the p-value. For a two-tailed test, we need to multiply the value by 2, as follows:
scipy.stats.t.sf(abs(t), df)*2Here, t is the test statistic and df is the degree of freedom (df = n-1 where n is the sample size).
To compute the critical value in Python, we use the following syntax:
scipy.stats.t.ppf(q, df)Here, q is the level of significance and df is the degree of freedom to be used in the formula. Here is the implementation of the code in Python for left-tailed, right-tailed, and two-tailed tests:
import scipy.stats as statsalpha = 0.05 # level of significancedf= 15 # degree of freedom#find t critical value for left-tailed testprint(f" The critical value is {stats.t.ppf(q= alpha, df =df)}")#find t critical value for right-tailed testprint(f" The critical value is {stats.t.ppf(q= 1-alpha, df =df)}")##find t critical value for two-tailed testprint(f" The critical values are {-stats.t.ppf(q= 1-alpha/2, df =df)} and {stats.t.ppf(q= 1-alpha/2, df =df)}")This is the output of the preceding code:
- The critical value is -1.7530503556925552
- The critical value is 1.7530503556925547
- The critical values are -2.131449545559323 and 2.131449545559323
At the level of significance, for the left-tailed test, the critical value is about -1.753. Since this is a left-tailed test, if the test statistic is less than or equal to this critical value, we reject the null hypothesis. Similarly, for the right-tailed test, if the test statistic is greater than or equal to 1.753, we reject the null hypothesis. For the two-tailed test, we reject the null hypothesis if the test statistic is greater than or equal to 2.1314 or less than or equal to -2.1314. Finally, we interpret the statistical conclusion for the hypothesis testing.
Let us randomly choose 30 students from a high school and score their IQ. We would like to test the claim that the mean IQ score of the distribution of the students from this high school is higher than 100. This means that we will perform a right-tailed t-test. The IQ scores of 30 students are given here:
IQscores = [113, 107, 106, 115, 103, 103, 107, 102, 108, 107, 104, 104, 99, 102, 102, 105, 109, 97, 109, 103, 103, 100, 97, 107,116, 117, 105, 107, 104, 107]Before conducting the hypothesis testing, we will check normality and independence assumptions. The assumption of independence is satisfied if the sample is randomly selected from the population of high school students at this school. For normality, we will check the histogram and QQ plots of IQ score data:

Figure 4.10 – Visually assessing normality of student IQ scores
There is little to no evidence from the histogram and QQ plot that the population IQ score distribution of the students at the high school is not normal. Since the distribution is assumed to be normal, we will proceed with the t-test.
First, we define the null hypothesis and the alternative hypothesis:
We choose the level of significance =0.05. You can calculate the test statistic by using its mathematical formula by hand or by implementing Python. For the critical value and p-value, the implemented code was shown in the previous part. Here, we will use another function from the scipy library to find the test statistic and p-value:
scipy.stats.ttest_1samp(data, popmean, alternative='greater')Here, the following applies:
data: The observations from the samplepopmean: The expected value in the null hypothesisalternative:'two-sided'for a two-tailed t-test,'less'for a left-tailed t-test, and'greater'for a right-tailed t-test
The Python code is implemented as follows:
import scipy.stats as stats#perform one sample t-testt_statistic, p_value = stats.ttest_1samp(IQscores, popmean =100, axis=0, alternative='greater')print(f"The test statistic is {t_statistic} and the corresponding p-value is {p_value}.")This is the output:
The test statistic is 6.159178830896832 and the corresponding p-value is 5.15076734562176e-07.
Because the p-value < 0.05 where 0.05 is the level of significance, we have enough evidence to reject the null hypothesis and conclude that the true mean IQ scores of the students from this school is higher than 100.
In addition, with 95% confidence, the mean IQ score lies between 104.08 and 107.12. We can perform the calculation for the confidence interval in Python as follows:
IQmean = np.array(IQscores).mean() # sample meanIQsd = np.array(IQscores).std() # sample standard deviationsample_size = len(np.array(IQscores)) # sample sizedf = sample_size-1 # degree of freedomalpha = 0.05 # level of significancet_crit = stats.t.ppf(q=1-alpha, df =df) # criticalconfidence_interval = (IQmean-IQsd*t_crit/np.sqrt(sample_size), IQmean+IQsd*t_crit/np.sqrt(sample_size))The steps to perform a hypothesis test in Python using the left-tailed t-test are similar to those of the right-tailed and two-tailed t-tests.
Two-sample t-test – pooled t-test
Section titled “Two-sample t-test – pooled t-test”Similar to what was covered in Chapter 3*, Hypothesis Testing,* (two-sample z-test for means), the two-sample t-test for means has three forms for the null and alternative hypotheses. Some assumptions need to be satisfied before conducting the test, as follows:
- Normality: Two samples are drawn from their normally distributed populations
- Independence: The observations of one sample are independent of one another
- Homogeneity of variance: Both populations are assumed to have similar standard deviations
For normality, we use visual histograms and also QQ plots of the two samples and compare them. Let us assume independence is satisfied. In order to check equal standard deviations between the two samples, we could use visualization by observing their histograms and also use an F-test to have additional evidence if the visualization is inconclusive. This is a hypothesis test to check whether two sample variances are equal.
Let us look at the IQ scores between two high schools, A and B. The following are the scores of 30 students from each school, randomly selected:
IQscoresA=[113, 107, 106, 115, 103, 103, 107, 102,108, 107, 104, 104, 99, 102, 102, 105, 109, 97, 109, 103, 103, 100, 97, 107, 116, 117, 105, 107, 104, 107]IQscoresB = [102, 108, 110, 101, 98, 98, 97, 102, 102, 103, 100, 99, 97, 97, 94, 100, 104, 98, 92, 104, 98, 95, 92, 111, 102, 112, 100, 103, 103, 100]The histograms and QQ plots shown in Figure 4.11 are generated by the IQ data above.

Figure 4.11 – Assessing normality of two schools’ IQ scores
We can see that the normality assumption is satisfied. We also can assume by observing the histograms that the equal variance assumption is supported. Another F-test to check the equal variance assumption (if necessary) follows:
# F-testimport numpy as npimport scipy.stats as statsIQscoresA = np.array(IQscoresA)IQscoresB = np.array(IQscoresB)f = np.var(IQscoresA, ddof=1)/np.var(IQscoresB, ddof=1) # F statisticdfA = IQscoresA.size-1 #degrees of freedom AdfB = IQscoresB.size-1 #degrees of freedom Bp = 1-stats.f.cdf(f, dfA, dfB) #p-valueThe output of the preceding code tells us the F-test statistic is 0.9963 and the corresponding p-value is 0.50394 > 0.05 (0.05 is the level of significance), then we fail to reject the null hypothesis. This means that there is enough evidence to say that the standard deviations of these two samples are equal.
We now define the null hypothesis and the alternative hypothesis:
,
.
We choose the level of significance =0.05. We use the statsmodels.stats.weightstats.ttest_ind function to conduct the t-test. The documentation can be found here: https://www.statsmodels.org/dev/generated/statsmodels.stats.weightstats.ttest_ind.html.
We can use this function to perform three forms of the alternate hypothesis with alternative='two-sided', 'larger', or 'smaller'. In the pooled-variance t-test, when the assumption for equal variances is satisfied, the test statistic is computed as follows:
Here, are sample means, population means, and sample sizes of two samples, 1 and 2 respectively, and the pooled standard deviation is given here:
The degree of freedom is shown here:
Let’s go back to the example:
from statsmodels.stats.weightstats import ttest_ind as ttestt_statistic, p_value, degree_freedom = ttest(IQscoresA, IQscoresB, alternative='two-sided', usevar='pooled')The output returns the test statistic 3.78 and the p-value 0.00037, and the degrees of freedom used in the t-test are 58 (each sample size has 30 observations, then the degrees of freedom are calculated as 30 + 30 - 2 = 58).
Because the p-value <0.05, we reject the null hypothesis. There is sufficient evidence to suggest that there is a difference in mean IQ score between students at high schools A and B. To perform the confidence level, you can adapt the Python code in the last part of the one-sample t-test.
Recall that in some situations, if the histograms and QQ plots show some evidence of skewness, we can consider testing the medians instead of the means for hypothesis testing. As shown in Chapter 2*, Distributions of Data*, we can perform a data transformation (for example, log transformation) to obtain the normality assumption. After the transformation, the median of log(data) is equal to the mean of log(data). This means that the test is performed on means of the transformed data.
Two-sample t-test – Welch’s t-test
Section titled “Two-sample t-test – Welch’s t-test”This is a practical two-sample t-test when the data is normally distributed but the population standard deviations are unknown and unequal. We have the same assumption for normality as with a pooled t-test but we can relax the assumption for equal variance when performing Welch’s t-test. Let us consider the following example where we have two sample datasets:
sample1 = np.array([2,3,4,2,3,4,2,3,5,8,7,10])sample2 = np.array([30,26,32,34,28,29,31,35,36,33,32,27])We assume the independence is satisfied, but we will check the normality and equal standard deviation assumptions for these two samples, as follows:

Figure 4.12 – Checking equal variance for Welch’s t-test
There is strong visual evidence against equal standard deviations by looking at the x axis scale of the histograms in Figure 4*.12*. Let us assume the normality assumption is satisfied. In this case, a two-sample pooled t-test is not a good idea, but Welch’s t-test would suffice. The null and alternative hypotheses are given here:
We specify the level of significance 0.05. To calculate the test statistic and p-value, we implement the code as follows:
import scipy.stats as statst_statistic, p_value = stats.ttest_ind(sample1, sample2, equal_var = False)The test statistic is -22.47 and the p-value is <0.05 (the level of significance). We reject the null hypothesis. There is strong evidence to suggest the mean of sample data 1 is different from the mean of sample data 2.
Paired t-test
Section titled “Paired t-test”The paired t-test is also known as a matched pairs or dependent t-test and is used in studies when each element in a sample is tested twice (pre-test and post-test or repeated measures) and when the researcher thinks that there are some similarities, such as family. The assumptions are set out here:
- Differences are normally distributed
- Differences are independent between observations but dependent from one test to another test
The paired t-test is used in many studies, especially in medical reasoning tests related to pre- and post-treatments. Let’s go back to IQ test scores—a researcher recruits a number of students to see whether there is a score difference before and after a training section, as represented in the following table:
| Students | Pre-training score | Post-training score | Differences |
|---|---|---|---|
| A | 95 | 95 | 0 |
| B | 98 | 110 | 12 |
| C | 90 | 97 | 7 |
| D | 115 | 112 | -3 |
| E | 112 | 117 | 5 |
Figure 4.13 – Pre-training and post-training scores
In this case, we should not use an independent two-sample t-test. The mean of the differences should be tested here. We can check the assumption about normal distribution by using histogram and QQ plots, as follows:

Figure 4.14 – Checking normality for the paired t-test
Evidence for the data being normally distributed is more obvious by looking at the QQ plot than the histogram.
The differences are assumed to be independent. The null and alternative hypotheses are given here:
denotes the difference between the pre-training score and the post-training score of each student. The null and alternative hypotheses can be rewritten as follows:
Then, the test statistic is computed like so:
Here, is the sample mean of the differences and is the sample standard deviation of differences. In other words, a paired t-test is reduced to a one-sample t-test. However, we can use the following function in scipy directly:
stats.ttest_rel(data_pos, data_pre, alternative = {'two-sided', ' less', 'greater'})
The alternative hypothesis corresponds to a left-tailed, right-tailed, or two-tailed test. Here is the Python implementation for the IQ test score study example:
from scipy import statsIQ_pre = [95, 98, 90, 115, 112]IQ_pos = [95, 110, 97, 112, 117]t_statistic, p_value = stats.ttest_rel(IQ_pos, IQ_pre, alternative = 'greater')The test statistic is 1.594 and the p-value is 0.093. Therefore, given the p-value is <0.05 and the level of significance we reject the null hypothesis. There is sufficient evidence to suggest that training has a significant effect on IQ scores.
Tests with more than two groups and ANOVA
Section titled “Tests with more than two groups and ANOVA”In the previous chapter and previous sections, we covered tests between two groups. In this section, we will cover two methods for testing differences between groups, as follows:
- Pairwise tests with the Bonferroni correction
- ANOVA
When testing for differences between more than two groups, we will have to use multiple tests, which will affect our type I error rate. There are several methods to control the error rate. We will see how to utilize the Bonferroni correction to control the Type I error rate. We will also discuss ANOVA in this section, which is used to test for a difference in means of multiple groups.
Multiple tests for significance
Section titled “Multiple tests for significance”In the previous sections, we looked at making a comparison between two groups. In this section, we will consider how to perform tests when there are more than two groups present. Let’s again consider the factory example where we have several models (model A, model B, and model C) of machines on a factory floor, and these machines are used to perform the same operation in the factory. A plausible question of interest is: Does one machine model have a higher mean output than the other two models? To make this determination, we would need to do three tests comparing the difference in means of each model to the other models, testing that the difference in means is different than zero. These are the null hypotheses we would need to test:
When performing multiple tests, we will need to apply p-value corrections for our expected error rate. Recall that in Chapter 3*, Hypothesis Testing*, we defined the expected error rate for a hypothesis test as. This is the rate at which we expect a single hypothesis test to result in a Type I error. In our example with factory machines, we are making three hypothesis tests, which means we are three times more likely to see a Type I error. While our example specifically considers multiple tests for differences in means, this applies to any type of hypothesis test. In these situations with multiple tests, we will generally define a familywise error rate (FWER) and apply p-value corrections to control for the FWER. The FWER is the probability of making a Type I error from a group of hypothesis tests. The error rate from tests within the group is the individual error rate (IER). We will define the IER and FWER as follows:
- IER: The expected Type I error rate for an individual hypothesis test
- FWER: The expected Type I error rate for a group of hypothesis tests
We will discuss one method for p-value correction in this section to provide intuition for the rationale.
The Bonferroni correction
Section titled “The Bonferroni correction”One method for adjusting the p-value to control multiple hypothesis tests is the Bonferroni correction. The Bonferroni correction controls the FWER by uniformly reducing the significance level of each individual test in the family of tests. Given that we have tests in a family each with the p-value, then the p-value correction is given as follows:
Taking our previous example of three models of machines, we have a family of three tests, making. If we let FWER be 0.05, then, with the Bonferroni correction, the level of significance for the three individual tests is this:
Thus, in this example, any of the individual tests would be required to have a p-value of 0.0167 to be considered significant.
Effects on Type I and Type II errors
As discussed, the Bonferroni correction reduces the significance levels of individual tests to control the Type I error rate at the family level. We should also consider how this change impacts the Type II error rate. In general, reducing the significance level of individual tests will increase the chance of making a Type II error for that test (as is done in the Bonferroni correction). While we have only discussed the Bonferroni correction in this section, there are other methods for p-value correction that provide different trade-offs. Check the documentation of multipletests in statsmodels to see a list of p-value corrections implemented in statsmodels.
Let’s take a look at an example using the miles per gallon (MPG) data from the Auto MPG dataset from the UCI Machine Learning Repository, which can be found at this link: https://archive.ics.uci.edu/ml/datasets/Auto+MPG [1]. This dataset contains various attributes, including origin, mpg, cylinders, and displacement, for vehicles manufactured between 1970 and 1982. We will show an abbreviated form of the analysis here; the full analysis is included in the notebook in the code repository for this chapter.
For this example, we will use the mpg and origin variables, and test whether there is a difference in mpg from the different origins with a significance level of 0.01. The group means are shown in the following table (origin is an integer-encoded label in this dataset).
Vehicle origin (origin) | MPG (mpg) |
|---|---|
| 1 | 20.0 |
| 2 | 27.9 |
| 3 | 30.5 |
Figure 4.15 – Vehicle MPG means for each origin group
Running a t-test to compare each mean, we get the following p-values:
| Null hypothesis | Uncorrected p-value |
|---|---|
| 7.946116336281346e-12 | |
| 4.608511957238898e-19 | |
| 0.0420926104552266 |
Figure 4.16 – Uncorrected p-values for t-tests on the difference between each group
Applying the Bonferroni correction to the p-values, we get the following p-values:
| Null hypothesis | Corrected p-value (Bonferroni) |
|---|---|
| 2.38383490e-11 | |
| 1.38255359e-18 | |
| 0.126277831 |
Figure 4.17 – Corrected p-values for t-tests on the difference between each group
With the preceding p-values, reject the null hypothesis for a difference in the means of groups 1 and 2 and a difference in the means of groups 1 and 3, but fail to reject the null hypothesis for a difference in the means of groups 2 and 3 at our significance level of 0.01.
Other p-value correction methods
In this section, we only discussed one method for p-value correction—the Bonferroni correction—to provide intuition for the rationale of p-value corrections. However, there are other correction methods available that might be better suited for your problem. To see a list of p-value correction methods implemented within statsmodels, check the documentation of statsmodels.stats.multitest.multipletests.
In the previous section on multiple tests for significance, we saw how to perform multiple tests to determine whether means differed between groups. When dealing with means of groups, a useful first task is to conduct an analysis of variance. ANOVA is a statistical test for determining whether there is a difference between means of several groups. The null hypothesis is there is no difference in means, and the alternative hypothesis is the means are not all equal. Since ANOVA tests for a difference in means, it is commonly used before testing for a difference in means with pairwise hypothesis tests. If the ANOVA null hypothesis fails to be rejected, then there is no need to perform the pairwise tests. However, if the ANOVA null hypothesis is rejected, then pairwise tests can be performed to determine which specific means differ.
ANOVA versus pairwise tests
While pairwise testing is a general procedure for testing for differences between groups, ANOVA can only be used to test for differences in means.
In this example, we will again consider the MPG of vehicles from the Auto MPG dataset. Since we have already run pairwise tests and found a significant difference in the mean mpg of vehicles based on origin, we expect that ANOVA will provide a positive test result (reject the null hypothesis). Performing the ANOVA calculation, we get the following output. The small p-value suggests that we should reject the null hypothesis:
anova = anova_oneway(data.mpg, data.origin, use_var='equal')print(anova)# statistic = 98.54179491075868# pvalue = 1.915486418412936e-35The ANOVA analysis shown here is abbreviated. For the full code, see the associated notebook in the code repository for this chapter.
In this section, we covered methods for performing hypothesis tests for more than two groups of data. The first method was pairwise testing with p-value correction, which is a general method that can be used for any type of hypothesis test. The other method we covered was ANOVA, which is a specific test for differences in the means of groups. This is not a general method such as pairwise testing but can be used as a first step before performing pairwise tests for differences in means. In the next section, we cover another type of parametric test that can be used to determine whether two sets of data are correlated.
Pearson’s correlation coefficient
Section titled “Pearson’s correlation coefficient”Pearson’s correlation coefficient, also called Pearson’s r (or Pearson’s rho (ρ) when applied to population data) or the Pearson product-moment sample coefficient of correlation (PPMCC), is a bivariate test that measures the linear correlation between two variables. The coefficient produces a value ranging from -1 to 1 where -1 is a strong, inverse correlation and 1 is a strong, direct correlation. A zero-valued coefficient indicates no correlation between the two variables. Weak correlation is generally considered to be correlation between +/- 0.1 and +/- 0.3, moderate correlation is between +/- 0.3 and +/- 0.5, and strong correlation is between +/- 0.5 to +/- 1.0.
This test is considered parametric but does not require assumptions of normal distribution or homogeneity of variance. It is, however, required that data be independently sampled (both randomly selected and without serial correlation), have finite variance—such as with a distribution that has a very heavy tail—and be of a continuous data type. The test does not indicate an input variable and a response variable; it is simply a measure of the linear relation between two variables. The test uses standardized covariance to derive correlation. Recall that standardization requires dividing a value by the standard deviation.
The equation for the population Pearson’s coefficient,, is shown here:
Here, is the population covariance, calculated as follows:
The equation for the sample Pearson’s coefficient, r, is shown here:
Here, is the sample covariance, calculated as follows:
In Python, we can perform this test using the scipy scipy.stats.pearsonr function. In the following code snippet, we generate two normally distributed datasets of random numbers using numpy. We want to test the hypothesis that there is a correlation between the two groups since there is some significant overlap:
from scipy.stats import pearsonrimport matplotlib.pyplot as pltimport scipy.stats as statsimport seaborn as snsimport pandas as pdimport numpy as npmu1, sigma1 = 0, 1.1normally_distributed_1 = np.random.normal(mu1, sigma1, 1000)mu2, sigma2 = 0, 0.7normally_distributed_2 = np.random.normal(mu2, sigma2, 1000)df_norm = pd.DataFrame({'Distribution':['Distribution 1' for i in range(len(normally_distributed_1))] + ['Distribution 2' for i in range(len(normally_distributed_2))], 'X':np.concatenate([normally_distributed_1, normally_distributed_2])})In Figure 4*.18*, we can observe the overlapping variance of the two correlated distributions:

Figure 4.18 – Correlated distributions
In the plot shown in Figure 4*.18*, we can see the overlap of the populations. Now, we want to test the correlation using the pearsonr() function, as follows:
p, r = pearsonr(df_norm.loc[df_norm['Distribution'] == 'Distribution 1', 'X'], df_norm.loc[df_norm['Distribution'] == 'Distribution 2', 'X'])print("p-value = %.4f"%p)print("Correlation coefficient = %.4f"%r)The following output indicates that at a 0.05 level of significance, we have a 0.9327 level of correlation (p-value is 0.0027):
p-value = 0.0027
Correlation coefficient = 0.9327
To frame the correlation differently, we could say the level of variance explained (, also called goodness-of-fit or the coefficient of determination) in distribution 2 by distribution 1 is, assuming we know that distribution 2 is a response to distribution 1. Otherwise, we could simply say there is a correlation of 0.93 or an 87% level of variance explained in the relationship between the two variables.
Now, let us look at the Motor Trend Car Road Tests dataset from R, which we import using the statsmodels datasets.get_rdataset function. Here, we have the first five rows, which have the variables for miles per gallon (mpg), number of cylinders (cyl), engine displacement (disp), horsepower (hp), rear-axle gear ratio (drat), weight (wt), minimum time to drive a quarter of a mile (qsec), engine shape (vs=0 for v-shaped and vs=1 for inline), transmission (am=0 for automatic and am=1 for manual), number of gears (gear), and number of carburetors (carb) (if not fuel injected):
import statsmodels.api as smdf_cars = sm.datasets.get_rdataset("mtcars","datasets").dataIn Figure 4.19, we can see the first five rows of the data set, which contains data suitable for Pearson’s correlation analysis.
| mpg | cyl | disp | hp | drat | wt | qsec | Vs | am | gear | carb |
|---|---|---|---|---|---|---|---|---|---|---|
| 21 | 6 | 160 | 110 | 3.9 | 2.62 | 16.46 | 0 | 1 | 4 | 4 |
| 21 | 6 | 160 | 110 | 3.9 | 2.875 | 17.02 | 0 | 1 | 4 | 4 |
| 22.8 | 4 | 108 | 93 | 3.85 | 2.32 | 18.61 | 1 | 1 | 4 | 1 |
| 21.4 | 6 | 258 | 110 | 3.08 | 3.215 | 19.44 | 1 | 0 | 3 | 1 |
| 18.7 | 8 | 360 | 175 | 3.15 | 3.44 | 17.02 | 0 | 0 | 3 | 2 |
Figure 4.19 – first five rows from the mtcars dataset
Using the dataset, we can plot a correlation matrix with the following code, which shows each pairwise correlation for all features in the dataset to see how they relate to one another:
sns.set_theme(style="white")corr = df_cars.corr()f, ax = plt.subplots(figsize=(15, 10))cmap = sns.diverging_palette(250, 20, as_cmap=True)sns.heatmap(corr, cmap=cmap, vmax=.4, center=0, square=True, linewidths=.5, annot=True)Suppose we are curious about the variables most meaningful for quarter-mile time (qsec). In Figure 4*.20*, we can see by looking at the line for qsec that vs (v-shaped) is positively correlated at 0.74. Since this is a binary variable, we can assume, based on this dataset, that inline engines are faster than v-shaped engines. However, there are other covariates involved with significant correlation. For example, almost as strongly correlated with speed as engine shape is horsepower, such that as horsepower goes up, quarter-mile runtime goes down:

Figure 4.20 – Correlation matrix heatmap
A correlation matrix is useful for exploring the relationships between multiple variables at one time. It is also a useful tool for feature selection when building statistical and machine learning (ML) models, such as linear regression.
Power analysis examples
Section titled “Power analysis examples”Power analysis is a statistical method for identifying an appropriate sample size required for a hypothesis test to have sufficient power in preventing Type II errors – or failing to reject the null hypothesis when the null hypothesis should be rejected. Power analysis can also be used for identifying, based on sample size, a detectable effect size (or difference) between samples tested. In other words, based on a specific sample size and distribution, a power analysis can provide the analyst with a specific minimum difference the researcher may be able to reliably identify with a given test. In this section, we will demonstrate a power analysis using a one-sample t-test.
One-sample t-test
Section titled “One-sample t-test”Let’s assume a manufacturer sells a type of machine capable of producing 100,000 units per month with a standard deviation of 2,800 units. A company has bought a number of these machines and has found them to only be producing 90,000 units. The company wants to know how many of the machines are needed to determine with a high level of confidence the machines are not capable of producing 100,000 units. The following power analysis indicates that for a t-test, a sample of three machines is required to prevent, with an 85% probability, failing to identify a statistically significant difference in actual versus marketed machine performance when there is one:
from statsmodels.stats.power import TTestPowerimport numpy as np# Difference of distribution mean and the value to be assessed divided by the distribution standard deviationeffect_size = abs(100000-90000) / 2800powersTT = TTestPower()result = powersTT.solve_power(effect_size, nobs=3, alpha=0.05, alternative='two-sided')print('Power based on sample size:{}'.format(round(result,2)))# Power based on sample size: 0.85Additional power analysis example
Section titled “Additional power analysis example”To see additional examples of power analysis in Python, please refer to this book’s GitHub repository. There, we have examples for additional t-tests and F-tests, which focus on analyzing variance between sample groups.
Summary
Section titled “Summary”This chapter covered topics of parametric tests. Starting with the assumptions of parametric tests, we identified and applied methods for testing the violation of these assumptions and discussed scenarios where robustness can be assumed when the required assumptions are not met. We then looked at one of the most popular alternatives to the z-test, the t-test. We iterated through multiple applications of this test, covering one-sample and two-sample versions of this test using pooling, pairing, and Welch’s non-pooled version of the two-sample analysis. Next, we explored ANOVA techniques, where we looked at using data from multiple groups to identify statistically significant differences between them. This included one of the most popular adjustments to the p-value for when a high volume of groups is present—the Bonferroni correction, which helps prevent inflating the Type I error when performing multiple tests. We then looked at performing correlation analysis on continuous data using Pearson’s correlation coefficient and how to visualize correlation using a correlation matrix and accompanying heatmap. Finally, we briefly overviewed power analysis, with an example of performing this with a one-sample t-test. In the next chapter, we will discuss non-parametric hypothesis testing, including new tests in addition to those that pair with the parametric tests in this chapter for when assumptions cannot be safely assumed.
References
Section titled “References”[1] Dua, D. and Graff, C. (2019). UCI Machine Learning Repository [http://archive.ics.uci.edu/ml]. Irvine, CA: University of California, School of Information and Computer Science.