paired sign test in Python
from scipy.stats import binomtest, shapiro import numpy as np
alpha = 0.05
Example 1
before = np.array([120, 130, 135, 140, 135, 150, 140, 130, 145, 138])
after = np.array([118, 125, 130, 135, 133, 152, 137, 132, 146, 139])
differences = before - after
print(differences)

positive_diffs = np.sum(differences > 0)
negative_diffs = np.sum(differences < 0)
test_statistic = min(positive_diffs, negative_diffs)
print(test_statistic)

n = positive_diffs + negative_diffs
results = binomtest(test_statistic, n, p=0.5, alternative='two-sided')
p_value = results.pvalue
print(p_value)

if p_value < alpha: print("The median of the differences is not zero (there is a difference).") else: print("The median of the differences between the paired observations is zero (no difference)..")

Example 2 #one tail #zero value #shapiro #ordinal data
before = np.array([3, 4, 2, 4, 3, 4, 5, 3, 4, 2])
after = np.array([2, 4, 3, 5, 3, 5, 5, 4, 5, 3])
differences = before - after
print(differences)

shapiro_stat, shapiro_p_value = shapiro(differences)
print(shapiro_p_value)

positive_diffs = np.sum(differences > 0)
negative_diffs = np.sum(differences < 0)
test_statistic = min(positive_diffs, negative_diffs)
print(test_statistic)

n = positive_diffs + negative_diffs
print(n)

results = binomtest(test_statistic, n=n, p=0.5, alternative='less')
p_value = results.pvalue
print(p_value)

if p_value < alpha: print("The median of the differences is not zero (there is a difference which is less).") else: print("The median of the differences between the paired observations is zero (no difference)..")

Example statsmodel
import statsmodels from statsmodels.stats.descriptivestats import sign_test
before = np.array([120, 130, 135, 140, 135, 150, 140, 130, 145, 138])
after = np.array([118, 125, 130, 135, 133, 152, 137, 132, 146, 139])
sign_test(before, after)

Ryan is a Data Scientist at a fintech company, where he focuses on fraud prevention in underwriting and risk. Before that, he worked as a Data Analyst at a tax software company. He holds a degree in Electrical Engineering from UCF.