# Z-test >[!Abstract] The Z-test is used to determine whether two population means are different when the variances are known and the sample size is large. >The Z-test is formulated as: > $z = \frac{\bar{x} - \mu_0}{\sigma/\sqrt{n}} \sim N(0, 1)$ > Use When > - Comparing the impact of a certain drug on the mean of a sample, by using the mean of a population > - Comparing the mean value of a certain measure (eg. IQ) between two different groups ## Computing Z-tests Here is how we compute Z-tests using `python` ### One sample Z-test Suppose the IQ in a certain population is normally distributed with a mean of μ = 100 and standard deviation of σ = 15. A researcher wants to know if a new drug affects IQ levels, so he recruits 20 patients to try it and records their IQ levels. The following code shows how to perform a one sample z-test in Python to determine if the new drug causes a significant difference in IQ levels: ```python from statsmodels.stats.weightstats import ztest as ztest #enter IQ levels for 20 patients data = [88, 92, 94, 94, 96, 97, 97, 97, 99, 99, 105, 109, 109, 109, 110, 112, 112, 113, 114, 115] #perform one sample z-test ztest(data, value=100) ``` ``` (1.5976240527147705, 0.1101266701438426) ``` The test statistic for the one sample z-test is **1.5976** and the corresponding p-value is **0.1101**. Since this p-value is not less than .05, we do not have sufficient evidence to reject the null hypothesis. In other words, the new drug does not significantly affect IQ level. ### Two sample Z-test Suppose the IQ levels among individuals in two different cities are known to be normally distributed with known standard deviations. A researcher wants to know if the mean IQ level between individuals in city A and city B are different, so she selects a simple random sample of  20 individuals from each city and records their IQ levels. The following code shows how to perform a two sample z-test in Python to determine if the mean IQ level is different between the two cities: ```python from statsmodels.stats.weightstats import ztest as ztest #enter IQ levels for 20 individuals from each city cityA = [82, 84, 85, 89, 91, 91, 92, 94, 99, 99, 105, 109, 109, 109, 110, 112, 112, 113, 114, 114] cityB = [90, 91, 91, 91, 95, 95, 99, 99, 108, 109, 109, 114, 115, 116, 117, 117, 128, 129, 130, 133] #perform two sample z-test ztest(cityA, cityB, value=0) (-1.9953236073282115, 0.046007596761332065) ``` The test statistic for the two sample z-test is **-1.9953** and the corresponding p-value is **0.0460**. Since this p-value is less than .05, we have sufficient evidence to reject the null hypothesis. In other words, the mean IQ level is significantly different between the two cities. ## Relations - [[Z-test for Proportions]] ## Resources - [How to Perform One Sample & Two Sample Z-Tests in Python](https://www.statology.org/z-test-python/)