Hypothesis Testing
local graph
Chapter 3 — Hypothesis Testing
Section titled “Chapter 3 — Hypothesis Testing”In this chapter, we will begin discussing drawing statistical conclusions from data, putting together sampling and experiment design from Chapter 1*, Sampling and Generalization* and distributions from Chapter 2*, Distributions of Data*. Our primary use of statistical modeling is to answer questions of interest from data. Hypothesis testing provides a formal framework for answering questions of interest with measures of uncertainty. First, we will cover the goals and structure of hypothesis testing. Then, we will talk about the errors that can occur from hypothesis tests and define the expected error rate. Then, we will walk through the hypothesis test process utilizing the z-test. Finally, we will discuss statistical power analysis.
In this chapter, we’re going to cover the following main topics:
- The goal of hypothesis testing
- Type I and type II errors
- Basics of the z-test – the z-score, z-statistic, critical values, and p-values
- One-sample and two-sample z-tests for means and proportions
- Selecting error rate and power analysis
- Applying the power analysis to the z-test
The goal of hypothesis testing
Section titled “The goal of hypothesis testing”Put simply, the goal of hypothesis testing is to decide whether the data we have is sufficient to support a particular hypothesis. The hypothesis test provides a formal framework for testing a hypothesis based on our data rather than attempting to decide based on visual inspection. In this section, we will discuss the process of hypothesis testing. In the next section, Basics of the z-test – the z-score, z-statistic, critical values, and p-values, we will put the process to work by walking through an example in detail with the z-test.
Overview of a hypothesis test for the mean
Section titled “Overview of a hypothesis test for the mean”To understand the hypothesis testing process, let’s start with a simple example. Suppose we have a factory with machines that produce widgets, and we expect our machines to produce widgets at a certain rate (30 widgets per hour). We start by constructing two hypotheses, the null hypothesis and the alternative hypothesis. The null hypothesis and alternative hypothesis are given the following symbols, respectively: and. To create the null hypothesis, we will start by assuming what we want to test is true. In our example, the null hypothesis would be that the machines output a mean of 30 widgets per hour. Once we have determined the null hypothesis, we then create the alternative hypothesis, which is just the contradiction of the null hypothesis. In our example, the alternative hypothesis is that the machines do not output a mean of 30 widgets per hour. Notice that our hypotheses do not indicate any directionality, that is, the alternative hypothesis contains values both less than and greater than the expected value. This is called a two-sided test, meaning there are two alternatives to the null hypothesis. We also have one-sided tests. For example, if we had said the null hypothesis was that the machines output more than a mean of 30 widgets per hour, the alternative would be that the machines output less than a mean of 30 widgets per hour. This set of hypotheses would be a one-sided test.
The two-sided null hypothesis and alternative hypothesis from our example can be stated mathematically as follows:
H 0: _ x = 30
H a: _ x ≠ 30
Once we have the null and alternative hypotheses and the data, we will run the test with software. Let’s set the implementation details of the test aside for now (these will be covered in detail in the next section). There are two possible outcomes of a statistical test: reject the null hypothesis or fail to reject the null hypothesis. If the mean output of our machines is statistically different from the stated value in the null hypothesis, then we will reject the null hypothesis. This means that, given the data, the value stated in the null hypothesis is not a plausible value for the mean. However, if the mean output of our machines is not statistically different from the value listed in the null hypothesis, we fail to reject the null hypothesis. This means that, given the data, the value stated in the null hypothesis is a plausible value for the mean. After running the test for the null hypothesis and determining the conclusion, we will provide a confidence interval (discussed in the next section) and determine the scope of inference.
Scope of inference
Section titled “Scope of inference”The scope of inference is determined by the sampling design discussed in Chapter 1. There are two questions to consider – what is the population, and how was the sample selected from the population? In this example, let’s assume that we are testing the mean output of machines from a large factory (possibly hundreds of machines). The population is then the machines in the factory. If we take a random sample of machines, then our conclusion can be extrapolated to the entire population.
While our current example is realistic, it is rather simple. In other scenarios, there may be additional considerations. For example, the machines in the factory may have different models and different ages, which may impact output. In that case, we could use stratified random sampling and make inferences for each stratum.
Hypothesis test steps
Section titled “Hypothesis test steps”This section provides an overview of hypothesis testing from creating a hypothesis to drawing a conclusion. As we continue through this chapter, keep the following key hypothesis test steps in mind:
- State the null hypothesis and alternative hypothesis
- Perform the statistical test
- Determine the conclusion: reject or fail to reject the null hypothesis
- Provide a statistical conclusion, a confidence interval, and a scope of inference
These steps are applicable to any statistical test, and we will continue to follow this series of steps for hypothesis tests. In the next section, we will discuss the types of errors that can result from hypothesis tests.
Type I and Type II errors
Section titled “Type I and Type II errors”While data can give us a good idea of the characteristics of a distribution, it is possible for a hypothesis test to result in an error. Errors can occur because we are taking a random sample from a population. While randomization makes it less likely that a sample contains sampling bias, there is no guarantee that a random sample will be representative of the population. There are two possible errors that could occur as a result of a hypothesis test:
- Type I error: Rejecting the null hypothesis when it is actually true
- Type II error: Failure to reject the null hypothesis when it is actually false
Type I errors
Section titled “Type I errors”A type I error occurs when a hypothesis test results in rejecting the null hypothesis, but the null hypothesis is actually true. For example, say we have a distribution of data with a population mean of 30. We state our null hypothesis as. We take a random sample for our test, but the random values in the sample happen to be on the higher side of the distribution. Thus, the test result suggests that we should reject the null hypothesis. In this case, we have made a type I error. This type of error is also called a false positive.
When we make statistical tests, it is always possible that we will come to an incorrect conclusion due to the data sampled from the target population. The probability of making a type one error is specified by. Said another way, represents how often we expect to make an error (the expected error rate). This is a free parameter we can select for our test ( is also called the level of significance). It is common to use 0.05 for, but there is no evidential basis for using 0.05; different values may be appropriate in other contexts. Later in the chapter, we will discuss selecting the type I error rate.
Type II errors
Section titled “Type II errors”The other type of error we can make is called a type II error. In this case, we fail to reject the null hypothesis when it is actually false. Let’s consider another example. Say we have a distribution of data and we want to test whether the mean of the distribution is 30 or not. We take a random sample for the test and the test suggests that we should not reject the null hypothesis. However, the true population mean is 35. In this case, we have made a type II error. This type of error is also called a false negative.
As mentioned previously, it is always possible that a statistical test could lead to an erroneous conclusion. Thus, we want to control the probability of making an error. However, unlike, the Type II error rate is not simply a free parameter that we can select. To understand the likeliness of making a type II error, we generally will conduct a power analysis, which will show how various factors, such as sample size, will impact the type II error rate. In the next section, we will discuss selecting the error rate and power analysis.
We can summarize the possible results of a hypothesis test with the help of the table in Figure 3*.1*.
Null Hypothesis is: | |||
True | False | ||
Decision about Null Hypothesis | Don’t Reject | Correct Inference (1- α) | Type II Error (β) |
Reject | Type I Error (α) | Correct Inference (1-β) | |
Figure 3.1 – Results of the hypothesis test
In this section, we have discussed the types of errors that can occur when drawing conclusions from statistical tests. In the next section, we will walk through an example of hypothesis testing with the z-test and later in the chapter, we will discuss how to select an error rate and how to analyze statistical power and related factors.
Basics of the z-test – the z-score, z-statistic, critical values, and p-values
Section titled “Basics of the z-test – the z-score, z-statistic, critical values, and p-values”In this section, we will discuss a type of hypothesis test called the z-test. It is a statistical procedure using sample data assumed to be normally distributed to determine whether a statistical statement related to the value of a population parameter should be rejected or not. The test can be performed on the following:
- One sample (a left-tailed z-test, right-tailed z-test, or two-tailed z-test)
- Two samples (a two-sample z-test)
- Proportions (a one-proportion z-test or two-proportion z-test)
The test assumes that the standard deviation is known and the sample size is large enough. In practice, a sample size that is larger than 30 should be considered.
Before going into different types of z-tests, we will discuss the z-score and z-statistic.
The z-score and z-statistic
Section titled “The z-score and z-statistic”To measure how far a particular value from a mean is, we could use the z-score or the z-statistic as statistical techniques together with the mean and the standard deviation to determine the relative location.
A z-score is computed with the following formula:
Here, is the z-score for, is the sample mean, and is the sample standard deviation. The z-score is also known as the z-value, standardized value, or standard score. Let’s consider a few examples. The standard deviation tells us how far a sample is from the mean of the distribution. If, that point is 1.8 standard deviations away from the mean. Similarly if then that point is 1.5 standard deviations away from the mean. The sign of the determines whether it is greater or less than the sample mean. A of -1.5 is less than the mean and a of 1.8 is greater than the mean. Now let us go through an example. In a high school in Dallas (in the US), we ask students to take anonymous IQ tests for some statistical research. The data collected from that school is normally distributed with an IQ score population mean and a population standard deviation A particular student took an IQ test and his score is 110. He has an IQ score greater than the score mean but he wants to know whether he is in the top 5%. First, we will use the z-score formula to calculate it:
.
The student can check a z-table (Figure 3*.2*), for example, from the website http://www.z-table.com, and get the value of 0.8413. He is in the top 1-0.8413 = 0.1587 or 15.87% of his school IQ scores.

Figure 3.2 – z-table
In Python, we can use the cumulative distribution function (CDF) to calculate it:
import scipyround(scipy.stats.norm.cdf(1),4)We also get the same value in Python as in the z-table check; it is 0.8413 for the z-score = 1 in this example.
Another example here is a simple random sample of 10 scores taken from the IQ survey:
90, 78, 110, 110, 99, 115, 130, 100, 95, 93
To compute the z-score for each IQ score in the sample, we need to calculate the mean and the standard deviation of this sample and then apply the z-score formula. Fortunately, we can use the scipy library again as follows:
import pandas as pdimport numpy as npimport scipy.stats as statsIQ = np.array([90, 78,110, 110, 99, 115,130, 100, 95, 93])z_score = stats.zscore(IQ)# Create dataframedata_zscore = { "IQ score": IQ, "z-score": z_score}IQ_zscore = pd.DataFrame(data_zscore)IQ_zscoreWe created an array of IQ scores called IQ and used z-score from scipy.stats to compute z_score. Finally, we created the following output DataFrame.

Figure 3.3 – Output DataFrame
Before discussing the z-statistic, we will introduce the notion of sampling distributions. Going back to the last example, as a rule of thumb, we perform the process of selecting a simple random sample of 35 IQ scores from the pool of IQ scores of the high school repeatedly, as many times as needed for the study. We then compute the mean score of each sample, called. Because we have various samples selected, we also have various possible values of. The expected value of is as follows:
Here, is the population mean. denotes the standard distribution of. Practically, in many sampling situations, a population is relatively large compared to small sample sizes. Then, the standard deviation of can be given as follows:
Here, is the population standard deviation and is the sample size for finite or infinite populations such that the population is large and the sample size is small, relatively. Note that is also called the standard error of the mean to help us determine how far the sample mean is from the population mean. Note that, independent of the sample size. Sample size and standard error are inversely correlated: when the sample size is increased, the standard error decreases. Since the sampling distribution of is assumed to be normally distributed, the sample distribution is given by the following formula:

In hypothesis tests about a population mean, we use test statistics where its formula is given as follows:
Here, is the sample mean, is the population mean, is the population standard deviation, and is the sample size.
Consider the IQ test example again. The IQ score data has a mean and a standard deviation Suppose the data is normally distributed. Let be the score taken randomly from the IQ data. What is the probability that is between 95 and 104? We will compute the z-scores when and as follows:
Therefore, the probability that the taken score is between 95 and 104 is:
Then, the probability is about 29.02% that an IQ score taken at random from the data is between 95 and 104. We also can get the values from a z-table as follows.

Figure 3.4 – z-table

Figure 3.5 – z-table
In Python, we can implement the code as follows:
#calculate z scores at x=95 and 104zscore_95 = round((95-98)/12,2)zscore_104 = round((104-98)/12,2)#calculate cdf and probabilitycdf_95 = stats.norm.cdf(zscore_95)cdf_104 = stats.norm.cdf(zscore_104)prob = abs(cdf_95-cdf_104)#print the probabilityprint(f"The probability that the taken score between 95 and 104 is {round(prob*100,2)}%!")Another question raised is what is the probability that the mean score of four scores taken randomly is between 95 and 104? To solve this question, we use the notion of the z-statistic. We assume the mean of is also 98 and has a normal distribution. Then, the standard error of is:
then:
It is easy to calculate and By using the z-table, we can get the probability that the mean score of six scores taken randomly is between 95 and 104 as follows:
0.8413 – 0.3085 = 0.5328
Or, about 53.28%. To use this idea, we can implement the code in Python as follows:
import pandas as pdimport numpy as npimport scipy.stats as statsimport math# standard errorn= 4sigma = 12se = sigma/math.sqrt(n)#calculate z scores at x=95 and 104zscore_95 = round((95-98)/se,2)zscore_104 = round((104-98)/se,2)#calculate cdf and probabilitycdf_95 = stats.norm.cdf(zscore_95)cdf_104 = stats.norm.cdf(zscore_104)prob = abs(cdf_95-cdf_104)#print the probabilityprint(f"The probability that the taken score between 95 and 104 is {round(prob*100,2)}%!")Note that in the preceding code, we also need the library called math for calculating the square root function, math.sqrt().
In the following section, we will discuss a z-test for means.
A z-test for means
Section titled “A z-test for means”In this part, one-sample and two-sample z-tests related to a population mean or means of two populations respectively are considered.
A one-sample z-test
Section titled “A one-sample z-test”A selected sample for research from a population should be normally distributed. The population standard deviation is supposed to be known, at least for practical purposes.
This test is still applicable in cases where the population cannot be assumed to be normally distributed but the sample size needs to be considered large enough by a rule of thumb, based on the experiences of researchers involved in the study. To perform the hypothesis testing, we need to develop the null and alternative hypotheses. The following figure illustrates three null and alternative hypotheses corresponding to left-tailed, right-tailed, and two-tailed z-tests.

Figure 3.6 – Left-tailed, right-tailed, and two-tailed hypothesis tests
H 0: μ ≥ μ 0 H 0: μ ≤ μ 0 H 0: μ = μ 0
H a: μ < μ 0 H a: μ > μ 0 H a: μ ≠ μ 0
Next, we need to specify the level of significance,, the probability of rejecting the null hypothesis when it is true. In other words, it is the probability of a type I error, aswe discussed in the last section. Then, we calculate the value of the test statistic. There are two approaches using a p-value or a critical value for the hypothesis testing.
In the p-value approach, we use the value of the test statistic to calculate a probability, denoted by the p-value, which takes on values as extreme as or more extreme than the test statistic derived from the sample. The smaller the p-value is, the more it indicates evidence against the null hypothesis, or in other words, the probability used to determine whether should be rejected. The rejection rule (reject ) is the p-value being less than or equal to the specified level of significance in the research. In order to find the p-value based on the value of the test statistic in Python, we use the following syntax:
scipy.stats.norm.sf(abs(x))Here, x is the z-score. For example, we want to find the p-value associated with a z-score of -2.67 in a left-tailed test. The Python implementation is as follows:
import scipy.stats#find p-valueround(scipy.stats.norm.sf(abs(-2.67)),4)The output will be 0.0038. Similar Python code is used in the case of a right-tailed test. For a two-tailed test, we need to multiply the value by 2:
#find p-value for two-tailed testscipy.stats.norm.sf(abs(2.67))*2The following figure illustrates the idea of how the p-value is computed in each type of test.

Figure 3.7 – p-values in hypothesis testing
The last step is to interpret the statistical conclusion.
On the other hand, in the critical value approach, we will need to compute a critical value for the test statistic by using the level of significance. Critical values are the boundaries of the critical region where we can reject the null hypothesis.

Figure 3.8 – Critical regions in hypothesis testing
To compute the critical value in Python, we use the following syntax:
scipy.stats.norm.ppf(alpha)Here, alpha is the level of significance to be used. The following is the implementation of the code in Python for left-tailed, right-tailed, and two-tailed tests:
import scipy.statsalpha = 0.05 # level of significance#find Z critical value for left-tailed testprint(f" The critical value is {scipy.stats.norm.ppf(alpha)}")#find Z critical value for left-tailed testprint(f" The critical value is {scipy.stats.norm.ppf(1-alpha)}")##find Z critical value for two-tailed testprint(f" The critical values are {-scipy.stats.norm.ppf(1-alpha/2)} and {scipy.stats.norm.ppf(1-alpha/2)}")Here’s the output of the preceding code:
The critical value is -1.6448536269514729
The critical value is 1.6448536269514722
The critical values are -1.959963984540054 and 1.959963984540054
At the level of significance for the left-tailed test, the critical value is about -1.64485. 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.64485, 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 1.95996 or less than or equal to -1.95996.
After determining whether to reject the null hypothesis, we interpret the statistical conclusion.
Let us discuss the IQ test scores again in the high school in Dallas. The IQ score data has a mean of and a standard deviation of A researcher wants to know whether IQ scores will be affected by some IQ training. He recruits 30 students and trains them to answer IQ questions 2 hours per day for 30 days and records their IQ levels after finishing the training period. The IQ scores of 30 students after the training section are 95, 110, 105, 120, 125, 110, 98, 90, 99, 100,110, 112, 106, 92, 108, 97, 95, 99, 100, 100,103, 125, 122, 110, 112, 102, 92, 97, 89, and 102. Their average score is 104.17. We can easily implement the calculation in Python as follows:
IQscores = [95,110, 105, 120, 125, 110, 98, 90, 99, 100, 110, 112, 106, 92, 108, 97, 95, 99, 100, 100, 103, 125, 122, 110, 112, 102, 92, 97, 89, 102]IQmean = np.array(IQscores).mean()We define the null hypothesis and the alternative hypothesis:
We choose the level of significance =0.05. Previously, the critical value for the right-tailed test was 1.64485. We now calculate the test statistic on the problem:
It is implemented in Python as follows:
n=30 #number of studentssigma =12 #population standard deviationIQmean = 104.17 # IQ mean of 30 students after the trainingmu = 98 # population meanz = (IQmean-mu)/(sigma/math.sqrt(n))Since the test statistic value is 2.8162 > 1.64485, we reject the null hypothesis. This means that the training does affect the IQ levels of these students and helps them improve their IQ scores.
We also can use the ztest() function from the statsmodels package (Seabold, Skipper, and Josef Perktold, “statsmodels: Econometric and statistical modeling with python.” Proceedings of the 9th Python in Science Conference. 2010) to perform one- or two-sample z-tests (which we will discuss in the next part). The syntax is as follows:
statsmodels.stats.weightstats.ztest(x1, x2=None, value=0, alternative='two-sided')Here, we see the following:
x1: The first of the two independent samplesx2: The second of the two independent samples (if performing a two-sample z-test)value: In the one -sample case,valueis the mean ofx1under the null hypothesis. In the two-sample case,valueis the difference between the mean ofx1and the mean ofx2under the null hypothesis. The test statistic isx1_mean - x2_mean -value.alternative: The alternative hypothesis:'two-sided': Two-sided test'larger': Right-tailed test'smaller': Left-tailed test
The following Python code shows how we perform a one-sample z-test:
from statsmodels.stats.weightstats import ztest as ztest#IQ scores after training sectionsIQscores = [95,110, 105, 120, 125, 110, 98, 90, 99, 100, 110, 112, 106, 92, 108, 97, 95, 99, 100, 100, 103, 125, 122, 110, 112, 102, 92, 97, 89, 102]#perform one sample z-testz_statistic, p_value = ztest(IQscores, value=98, alternative = 'larger')print(f"The test statistic is {z_statistic} and the corresponding p-value is {p_value}.")The test statistic is 3.3975 and the p-value = 0.00034 < 0.05, where 0.05 is the level of significance. Therefore, we have enough evidence to reject the null hypothesis. This means that the training does affect the IQ levels of these students.
Two-sample z-test
Section titled “Two-sample z-test”We consider two normally distributed and independent populations. Let be the hypothesized difference between two population means, and Similarly, as in the case of the one-sample z-test, we have three forms for the null and alternative hypotheses:
In many problems, That means that for the case of the two-tailed test, the null hypothesis is zero, or in other words, and are equal. The test statistic for hypothesis tests is computed as follows:
Here, and are the sample means with the sample sizes and randomly taken from the two populations with the means and, respectively. and are the standard deviations for these two populations. With two independent simple random samples, the point estimator has a standard error given as follows:
The distribution of can be considered a normal distribution when the sample sizes are large enough. The step-by-step approach to the two-sample z-test hypothesis test is similar to that of the one-sample z-test.
Let us now consider an example. We study the IQ scores of students from two schools, named A and B, in Dallas, and we want to know whether the mean IQ levels for these two schools are different. A simple random sample of 30 students from each school is recorded.
A= [95,110, 105, 120, 125, 110, 98, 90, 99, 100,110, 112, 106, 92, 108, 97, 95, 99, 100, 100, 103, 125, 122, 110, 112, 102, 92, 97, 89, 102]
B = [98, 90, 100, 93, 91, 79, 90, 100, 121, 89, 101, 98, 75, 90, 95, 99, 100, 120, 121, 95,
96, 89, 115, 99, 95, 121, 122, 98, 97, 97]
The null and alternative hypotheses are:
We choose the level of significance =0.05. In Python, by using the ztest() function of the statsmodels package, we perform the following calculation:
from statsmodels.stats.weightstats import ztest as ztest#IQ scoreA= [95,110, 105, 120, 125, 110, 98, 90, 99, 100, 110, 112, 106, 92, 108, 97, 95, 99, 100, 100, 103, 125, 122, 110, 112, 102, 92, 97, 89,102] #school AB = [98, 90, 100, 93, 91, 79, 90, 100, 121, 89, 101, 98, 75, 90, 95, 99, 100, 120, 121, 95, 96, 89, 115, 99, 95, 121, 122, 98, 97, 97] # school B#perform two- sample z-testz_statistic, p_value = ztest(A, B, value=0, alternative = 'two-sided')print(f"The test statistic is {z_statistic} and the corresponding p-value is {p_value}.")In the preceding code, we chose alternative = 'two-sided' related to the null and alternative hypotheses for the study. The test statistic and the p-value produced by the Python code are 1.757 and 0.079, respectively. Using a level of significance of 0.05, since the p-value > 0.05, we fail to reject the null hypothesis. In other words, we do not have enough evidence to show that the IQ mean scores between the students from the two schools are different.
z-test for proportions
Section titled “z-test for proportions”We can also test for differences in proportions. Let’s take a look at how to perform the z-test for proportions.
A one-proportion z-test
Section titled “A one-proportion z-test”One-proportion z-tests are used to compare the difference between a sample proportion and a hypothesized proportion Similarly, as in a z-test for means, we have three forms for the null and alternative hypotheses – left-tailed, right-tailed, and two-tailed tests:
The test statistic is computed as follows:
Here, n is the sample size. Let us consider an example. In a community college in Houston, a researcher wants to know whether students support some changes equal to 80%. He will use a one-proportion z-test at the level of significance. To implement the code in Python, he can use proportions_ztest from the statsmodel library. The syntax is as follows:
statsmodels.stats.proportion.proportions_ztest(count, nobs, value=None, alternative='two-sided')count: The number of successesnobs: The number of trials or observationsvalue: This is the value of the null hypothesis, equal to the proportion in the case of a one-sample test. In the case of a two-sample test, the null hypothesis isprop[0] - prop[1] = value, wherepropis the proportion in the two samples. If not provided,value= 0, and the null hypothesis isprop[0] = prop[1].alternative: The alternative hypothesis:'two-sided': Two-sided test'larger': Right-tailed test'smaller': Left-tailed test
The researcher gathers a sample of data with an observed sample proportion p = 0.84, the hypothesized population proportion, and the sample size The null and alternative hypotheses are as follows:
We will implement a one-proportion two-tailed z-test in Python to calculate the test statistic and p-value:
#import proportions_ztest functionfrom statsmodels.stats.proportion import proportions_ztestcount = 0.8*500nobs = 500value = 0.84#perform one proportion two-tailed z-testz_statistic, p_value = proportions_ztest(count, nobs, value, alternative = 'two-sided')print(f"The test statistic is {z_statistic} and the corresponding p-value is {p_value}.")The test statistic is -2.236067977499786 and the corresponding p-value is 0.0253473186774685. Since the p-value < 0.05 (the level of significance), we reject the null hypothesis. There is enough evidence to suggest the proportion of students who support the changes is different from 0.8.
A two-proportion z-test
Section titled “A two-proportion z-test”This test is used to test the difference between two population proportions. There are also three forms of the null and alternative hypotheses. The test statistic is computed as follows:
Here, is a sample proportion for a simple random sample from population 1 and is a sample proportion for a simple random sample from population 2, and are the sample sizes, and is the total pooled proportion, calculated as follows:
We consider a similar example if there is a difference in the proportion of students from school A who support the changes compared to the proportion of students from school B. Here, You can use proportions_ztest from the statsmodels library (Seabold, Skipper, and Josef Perktold, “statsmodels: Econometric and statistical modeling with python.” Proceedings of the 9th Python in Science Conference. 2010) to perform the hypothesis test. Here, we will compute the p-value directly using the test statistic. The null and alternative hypotheses are as follows:
(The two population proportions are equal)
(The two population proportions are different)
Next, we specify that the level of significance for the two-tailed test is. We then calculate the test statistic and p-value as follows:
scipy.stats.norm.sf(abs(z))*2The test statistic is 1.633 and the p-value for a two-tailed test is 0.10. Because the p-value is greater than the specified level of significance, 0.05, we fail to reject the null hypothesis. There is enough evidence to say that the proportion of students who support the changes is different between school A and school B.
Finally, the implemented Python code for the preceding calculation is as follows:
import mathimport scipyp_1bar = 0.8p_2bar = 0.7n1 = 100.0n2 = 100.0p= (p_1bar*n1 + p_2bar*n2)/(n1+n2) # the total pooled proportionz = (p_1bar-p_2bar)/math.sqrt(p*(1-p)*(1/n1+1/n2))pval = scipy.stats.norm.sf(abs(z))*2print(f"The test statistic is {z} and the p-value for two tailed test is {pval}.")In this section, we went through different important statistical notions such as the z-score, z-statistics, critical values, p-value, and z-test for means and proportions. We will discuss selecting the error rate and power analysis in the next section.
Selecting the error rate and power analysis
Statistics generalizes approximations around which to form acceptable conclusions from behaviors in data. Therefore, errors in statistics are unavoidable. The significance of findings from statistical models is essentially determined by the error rate. One method that can be used to minimize errors in modeling, especially with lower sample volumes, is the power test. Statistical power is the probability of correctly rejecting a null hypothesis, thus minimizing type II errors. Where alpha (α) is a type I error and beta (β) is a type II error, power’s formulation is 1 – β. To refresh, a type I error is the probability of incorrectly rejecting the null hypothesis.
As noted, power is more important with smaller samples because the law of large numbers typically helps minimize errors as the sample size increases if an appropriate sampling method is chosen. Power is also important when the differences being compared are relatively small. One scenario in which power analysis may be particularly useful is when sampling is expensive, for example, with human studies. Power analyses can be used to find an appropriate minimum sample size given the desired power, type I error rate, and effect size. The relationship between these parameters can be explored as needed. Effect size is the difference or similarity of the data being compared in the hypothesis test, such as a standardized difference of means or correlation. As a common level of significance (type I error) in hypothesis testing is anywhere between 0.01 and 0.1, a common level of power is anywhere between 0.8 and 0.9, although these measures are case-dependent (https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7745163/#:~:text=The%20ideal%20power%20of%20a,high%20as%200.8%20or%200.9).
A few notable properties of power are as follows:
- There must be sufficient power to detect a meaningful difference
- Power increases with sample size
- Power increases with the effect size
- Standard deviation (as well as variance and standard error) decreases as power increases
In the following plot, we can see that type I error (α) is where we may falsely assume the null hypothesis and conclude there is no statistically significant difference when, in fact, the data points don’t belong to data source 2 (the null hypothesis), but to data source 1. Type II error (β) is where we might make the mistake of assuming the data in that region belongs to data source 1 (the alternate hypothesis) when, in fact, it belongs to data source 2.

Figure 3.9 – Visualizing error in a left-tailed two-population z-test
As illustrated in the preceding plot, we see a left-tailed t-test comparing the null distribution on the right to the alternate distribution on the left. In this plot, we can see two prominent concepts at hand:
- As α becomes smaller, the critical value slides left, moving more toward distributional outliers, β becomes larger, and vice versa
- Statistical power is the area of data source 2 to the right of β, as *power = (*1-β)
A type I error is determined based on a pre-selected threshold; a researcher may feel most comfortable with a 90, 95, or 99% level of confidence. However, a type II error is based on parameterization (standard deviation, effect size, sample size, and so on). Therefore, we can use a power analysis to identify the sample size, and vice versa. The implementation of power analysis for various hypothesis tests will be implemented in the following two chapters.
Power analysis for a two-population pooled z-test
Section titled “Power analysis for a two-population pooled z-test”Let us look at a dataset of salaries for professors of two different disciplines, discipline A and discipline B. We want to know whether there is a statistically significant difference between them based on the data we have. First, we need to perform a power analysis to know whether we have enough samples to trust the results of the z-test we may perform to test this hypothesis. The components of a power analysis we need for this include effect size, the type I error rate, a desired type II error rate, the direction of the alternate hypothesis (group 2 is expected to be larger than, smaller than, or could be either larger or smaller than group 1), and the ratio of observations in the larger sample relative to that of the smaller. Discipline A has 181 salaries and discipline B has 216. Therefore, 216 will be our numerator corresponding to what we will consider as group 1 (discipline A will be group 2).
Let us suppose we are not sure whether one group will be larger or smaller than the other; we will consider this a two-sided hypothesis test. The effect size for this z-test is the difference between the two groups. We will use Cohen’s d. To calculate that, we need to divide the difference between the means of the two groups by the pooled standard deviation. Calculated here, the pooled standard deviation is the number of samples in group 1 multiplied by the variance of group 1, plus the same for group 2, all divided by the combined sample size for the two groups. The following is the equation for the pooled standard deviation:
For effect size, we need to divide the difference of means by the effect size as follows:
Note that in the equation for effect size, we take the absolute value of the difference of means. That is because, for Cohen’s d, we always need a positive difference of means for this test.
As calculated here, if we want a power of 80% (the type II error rate is 20%) and a type I error rate (a level of significance) of 0.05, we will need 172 samples in group 1 and 145 samples in group 2. However, if we wanted a power of 90% and a level of significance of 0.01 (99% confidence), we would need 325 samples in group 1 and 274 samples in group 2:
import statsmodels.api as smimport mathdf_prof = sm.datasets.get_rdataset("Salaries", "carData").datadf_prof_A = df_prof.loc[df_prof['discipline'] == 'A']df_prof_B = df_prof.loc[df_prof['discipline'] == 'B']def pooled_standard_deviation(dataset1, dataset2, column) -> float: pooledSD = math.sqrt(((len(dataset1) - 1)*(dataset1[column].std()**2)+(len(dataset2) - 1)*(dataset2[column].std()**2))/(len(dataset1) + len(dataset2) - 2)) return pooledSD;stdDeviation = pooled_standard_deviation( dataset1 = df_prof_A, dataset2=df_prof_B, column='salary')from statsmodels.stats.power import NormalIndPowereffect = abs(df_prof_B['salary'].mean() – df_prof_A['salary'].mean() ) / stdDeviation# The difference between two means divided by std if pooled 2-samplealpha = 0.05power = 0.8ratio=1.19 # # of obs in sample 2 relative to sample 1analysis = NormalIndPower()result = analysis.solve_power(effect, power=power, nobs1=None, ratio=ratio, alpha=alpha, alternative='two-sided')print('Sample Size Required in Sample 1: {:.3f}'.format( result*ratio)) # nobs1 is the sample size.print('Sample Size Required in Sample 2: {:.3f}'.format( result)) # nobs2 is the sample size.The output from this code is as follows:
Sample Size Required in Sample 1: 171.620Sample Size Required in Sample 2: 144.218effect = abs(df_prof_B['salary'].mean() – df_prof_A['salary'].mean() ) / stdDeviationalpha = 0.01power = 0.9ratio=1.19 # # of obs in sample 2 relative to sample 1analysis = NormalIndPower()result = analysis.solve_power(effect, power=power, nobs1=None, ratio=ratio, alpha=alpha, alternative='two-sided')print('Sample Size Required in Sample 1: {:.3f}'.format( result*ratio)) # nobs1 is the sample size.print('Sample Size Required in Sample 2: {:.3f}'.format( result)) # nobs2 is the sample size.The output of this code is as follows:
Sample Size Required in Sample 1: 325.346
Sample Size Required in Sample 2: 273.400
Summary
Section titled “Summary”In this chapter, we introduced the concept of a hypothesis test. We started with a basic outline of a hypothesis test with the four key steps:
- State the hypothesis
- Perform the test
- Determine whether to reject or fail to reject the null hypothesis
- Draw a statistical conclusion with a scope of inference
Then we talked about potential errors that can occur and false positives and false negatives and defined the expected error rate (alpha) of a test and the power (beta) of a test.
We also discussed the statistical procedure called the z-test. This is a type of hypothesis test using sample data assumed to be normally distributed. The z-score and z-statistic were also introduced in the section on different types of z-tests, such as one-sample or two-sample z-tests for means or proportions.
Finally, we discussed the concept and motivation behind the power analysis, which can be used to identify the probability of incorrectly rejecting the null hypothesis and selecting the sample size. We also explored the parameters of the analysis for a two-population pooled z-test. Here, we briefly examined effect size, which is the value of impact (the effect of a treatment) we search for when performing the hypothesis test. We will discuss power analysis in the next two chapters as we iterate over different applications of hypothesis testing.
In the next chapter, we will discuss more parametric hypothesis tests. While these tests will still require distribution assumptions, the assumptions will be less strict than the assumptions of the z-test.