How to do a Wilcoxon signed-rank test for matched pairs (in Python, using SciPy)
Task
Assume we have two samples of data that come in matched pairs,
Consider measuring the difference in each pair,
Related tasks:
- How to do a Kruskal-Wallis test
- How to do a Wilcoxon rank-sum test
- How to do a Wilcoxon signed-rank test
Solution
The method we will use is equivalent to subtracting the two samples and then performing the signed-rank test. See how to do a Wilcoxon signed-rank test to compare the two methods.
We’re going to use fake data for illustrative purposes, but you can replace our fake data with your real data.
1
2
3
4
import numpy as np
# Replace sample1 and sample2 with your data
sample1 = np.array([156, 133, 90, 176, 119, 120, 40, 52, 167, 80])
sample2 = np.array([45, 36, 78, 54, 12, 25, 39, 48, 52, 70])
We choose a value,
Two-tailed test
To test the null hypothesis
1
2
3
from scipy import stats
from scipy.stats import wilcoxon
wilcoxon(sample1 - sample2)
WilcoxonResult(statistic=0.0, pvalue=0.001953125)
Our p-value, 0.001953125, is less than
Right-tailed test
To test the null hypothesis
1
wilcoxon(sample1 - sample2, alternative = 'greater')
WilcoxonResult(statistic=55.0, pvalue=0.0009765625)
Our p-value, 0.0009765625, is less than
Left-tailed test
To test the null hypothesis
1
wilcoxon(sample1 - sample2, alternative = 'less')
WilcoxonResult(statistic=55.0, pvalue=1.0)
Our p-value, 1.0, is greater than
Content last modified on 24 July 2023.
See a problem? Tell us or edit the source.
Contributed by Elizabeth Czarniak (CZARNIA_ELIZ@bentley.edu)