How to conduct a Wilcoxon Signed-Rank Test in Python?

The Wilcoxon Signed-Rank Test is a non-parametric test that is used to compare two related samples of data. In Python, this test can be conducted by using the scipy.stats.wilcoxon() function, which takes in the two samples of data as parameters and returns the W statistic and the p-value. This W statistic and p-value are then used to determine if there is a statistically significant difference between the two samples.


The is the non-parametric version of the .

It is used to test whether or not there is a significant difference between two population means when the distribution of the differences between the two samples cannot be assumed to be normal.

This tutorial explains how to conduct a Wilcoxon Signed-Rank Test in Python.

Example: Wilcoxon Signed-Rank Test in Python

Researchers want to know if a new fuel treatment leads to a change in the average mpg of a certain car. To test this, they measure the mpg of 12 cars with and without the fuel treatment.

Use the following steps to perform a Wilcoxon Signed-Rank Test in Python to determine if there is a difference in the mean mpg between the two groups.

Step 1: Create the data.

First, we’ll create two arrays to hold the mpg values for each group of cars:

group1 = [20, 23, 21, 25, 18, 17, 18, 24, 20, 24, 23, 19]
group2 = [24, 25, 21, 22, 23, 18, 17, 28, 24, 27, 21, 23]

Step 2: Conduct a Wilcoxon Signed-Rank Test.

Next, we’ll use the  from the scipy.stats library to conduct a Wilcoxon Signed-Rank Test, which uses the following syntax:

wilcoxon(x, y, alternative=’two-sided’)

where:

  • x: an array of sample observations from group 1
  • y: an array of sample observations from group 2
  • alternative: defines the alternative hypothesis. Default is ‘two-sided’ but other options include ‘less’ and ‘greater.’

Here’s how to use this function in our specific example:

import scipy.stats as stats

#perform the Wilcoxon-Signed Rank Test
stats.wilcoxon(group1, group2)

(statistic=10.5, pvalue=0.044)

The test statistic is 10.5 and the corresponding two-sided p-value is 0.044.

In this example, the Wilcoxon Signed-Rank Test uses the following null and alternative hypotheses:

H0The mpg is equal between the two groups

HAThe mpg is not equal between the two groups

Since the p-value (0.044) is less than 0.05, we reject the null hypothesis. We have sufficient evidence to say that the true mean mpg is not equal between the two groups.

x