0
0
SciPydata~5 mins

Wilcoxon signed-rank test in SciPy

Choose your learning style9 modes available
Introduction

The Wilcoxon signed-rank test helps us check if two related sets of numbers are different in a way that is not just by chance.

Comparing before and after results of a diet on the same group of people.
Checking if a new teaching method changes test scores of the same students.
Testing if a medicine changes blood pressure by comparing measurements before and after treatment.
Comparing two related measurements like left and right hand strength of the same person.
Syntax
SciPy
from scipy.stats import wilcoxon

statistic, p_value = wilcoxon(x, y=None, zero_method='wilcox', correction=False, alternative='two-sided', mode='auto')

If you provide only one list x, it compares it to zero.

The alternative can be 'two-sided', 'greater', or 'less' to test different hypotheses.

Examples
This compares two lists of numbers from related samples.
SciPy
from scipy.stats import wilcoxon

# Compare two related samples
x = [5, 7, 8, 6, 9]
y = [6, 9, 7, 5, 10]
stat, p = wilcoxon(x, y)
print(stat, p)
This tests if the numbers in x are different from zero.
SciPy
from scipy.stats import wilcoxon

# Compare one sample to zero
x = [1, -1, 2, -2, 3]
stat, p = wilcoxon(x)
print(stat, p)
Sample Program

This program compares blood pressure readings before and after medicine for the same patients to see if the medicine made a difference.

SciPy
from scipy.stats import wilcoxon

# Data: blood pressure before and after medicine for 6 patients
before = [120, 130, 125, 140, 135, 128]
after = [118, 128, 130, 138, 133, 130]

stat, p_value = wilcoxon(before, after)

print(f"Wilcoxon statistic: {stat}")
print(f"p-value: {p_value}")
OutputSuccess
Important Notes

The test works best with paired data, meaning the two lists should be related.

A small p-value (usually less than 0.05) means there is a significant difference.

It does not assume the data follows a normal distribution, so it is good for small or non-normal data.

Summary

The Wilcoxon signed-rank test checks if two related samples differ.

It is useful when data is not normally distributed.

Use it for before-and-after or matched pair comparisons.