bundles / scipy latest / scipy / stats / _morestats / wilcoxon
function
scipy.stats._morestats:wilcoxon
source: build-install/usr/lib/python3.14/site-packages/scipy/stats/_morestats.py:3914
Signature
def wilcoxon(x, y = None, zero_method = wilcox, correction = False, alternative = two-sided, method = auto, *, axis = 0, nan_policy = propagate, keepdims = False)Summary
Calculate the Wilcoxon signed-rank test.
Extended Summary
The Wilcoxon signed-rank test tests the null hypothesis that two related paired samples come from the same distribution. In particular, it tests whether the distribution of the differences x - y is symmetric about zero. It is a non-parametric version of the paired T-test.
Parameters
x: array_likeEither the first set of measurements (in which case
yis the second set of measurements), or the differences between two sets of measurements (in which caseyis not to be specified.) Must be one-dimensional.y: array_like, optionalEither the second set of measurements (if
xis the first set of measurements), or not specified (ifxis the differences between two sets of measurements.) Must be one-dimensional.zero_method: {"wilcox", "pratt", "zsplit"}, optionalThere are different conventions for handling pairs of observations with equal values ("zero-differences", or "zeros").
"wilcox": Discards all zero-differences (default); see [4].
"pratt": Includes zero-differences in the ranking process, but drops the ranks of the zeros (more conservative); see [3]. In this case, the normal approximation is adjusted as in [5].
"zsplit": Includes zero-differences in the ranking process and splits the zero rank between positive and negative ones.
correction: bool, optionalIf True, apply continuity correction by adjusting the Wilcoxon rank statistic by 0.5 towards the mean value when computing the z-statistic if a normal approximation is used. Default is False.
alternative: {"two-sided", "greater", "less"}, optionalDefines the alternative hypothesis. Default is 'two-sided'. In the following, let
drepresent the difference between the paired samples:d = x - yif bothxandyare provided, ord = xotherwise.'two-sided': the distribution underlying
dis not symmetric about zero.'less': the distribution underlying
dis stochastically less than a distribution symmetric about zero.'greater': the distribution underlying
dis stochastically greater than a distribution symmetric about zero.
method: {"auto", "exact", "asymptotic"} or `PermutationMethod` instance, optionalMethod to calculate the p-value, see Notes. Default is "auto".
axis: int or None, default: 0If an int, the axis of the input along which to compute the statistic. The statistic of each axis-slice (e.g. row) of the input will appear in a corresponding element of the output. If
None, the input will be raveled before computing the statistic.nan_policy: {'propagate', 'omit', 'raise'}Defines how to handle input NaNs.
propagate: if a NaN is present in the axis slice (e.g. row) along which the statistic is computed, the corresponding entry of the output will be NaN.omit: NaNs will be omitted when performing the calculation. If insufficient data remains in the axis slice along which the statistic is computed, the corresponding entry of the output will be NaN.raise: if a NaN is present, aValueErrorwill be raised.
nan_policy='raise'andnan_policy='omit'are not supported by lazy backends, andnan_policy='omit'is not compatible with MArray input. For multidimensional input,nan_policy='omit'is supported only by the NumPy backend. Instead, mask NaN values using MArray; and use the defaultnan_policy. See Notes for support information.keepdims: bool, default: FalseIf this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
Returns
result: WilcoxonResultAn object with the following attributes.
statistic
If
alternativeis "two-sided", the sum of the ranks of the differences above or below zero, whichever is smaller. Otherwise the sum of the ranks of the differences above zero.pvalue
The p-value for the test depending on
alternativeandmethod.zstatistic
When
method = 'asymptotic', this is the normalized z-statisticz = (T - mn - d) / sewhere
Tisstatisticas defined above,mnis the mean of the distribution under the null hypothesis,dis a continuity correction, andseis the standard error. Whenmethod != 'asymptotic', this attribute is not available.
Notes
In the following, let d represent the difference between the paired samples: d = x - y if both x and y are provided, or d = x otherwise. Assume that all elements of d are independent and identically distributed observations, and all are distinct and nonzero.
When
len(d)is sufficiently large, the null distribution of the normalized test statistic (zstatisticabove) is approximately normal, andmethod = 'asymptotic'can be used to compute the p-value.When
len(d)is small, the normal approximation may not be accurate, andmethod='exact'is preferred (at the cost of additional execution time).The default,
method='auto', selects between the two:method='exact'is used whenlen(d) <= 50, andmethod='asymptotic'is used otherwise.
The presence of "ties" (i.e. not all elements of d are unique) or "zeros" (i.e. elements of d are zero) changes the null distribution of the test statistic, and method='exact' no longer calculates the exact p-value. If method='asymptotic', the z-statistic is adjusted for more accurate comparison against the standard normal, but still, for finite sample sizes, the standard normal is only an approximation of the true null distribution of the z-statistic. For such situations, the method parameter also accepts instances of PermutationMethod. In this case, the p-value is computed using permutation_test with the provided configuration options and other appropriate settings.
The presence of ties and zeros affects the resolution of method='auto' accordingly: exhaustive permutations are performed when len(d) <= 13, and the asymptotic method is used otherwise. Note that they asymptotic method may not be very accurate even for len(d) > 14; the threshold was chosen as a compromise between execution time and accuracy under the constraint that the results must be deterministic. Consider providing an instance of PermutationMethod method manually, choosing the n_resamples parameter to balance time constraints and accuracy requirements.
Please also note that in the edge case that all elements of d are zero, the p-value relying on the normal approximaton cannot be computed (NaN) if zero_method='wilcox' or zero_method='pratt'.
Beginning in SciPy 1.9, np.matrix inputs (not recommended for new code) are converted to np.ndarray before the calculation is performed. In this case, the output will be a scalar or np.ndarray of appropriate shape rather than a 2D np.matrix. Similarly, while masked elements of masked arrays are ignored, the output will be a scalar or np.ndarray rather than a masked array with mask=False.
Examples
In [4]_, the differences in height between cross- and self-fertilized corn plants is given as follows:d = [6, 8, 14, 16, 23, 24, 28, 29, 41, -48, 49, 56, 60, -67, 75]
✓from scipy.stats import wilcoxon res = wilcoxon(d)✓
res.statistic, res.pvalue
✗(np.float64(24.0), np.float64(0.041259765625))Hence, we would reject the null hypothesis at a confidence level of 5%, concluding that there is a difference in height between the groups. To confirm that the median of the differences can be assumed to be positive, we use:
res = wilcoxon(d, alternative='greater')
✓res.statistic, res.pvalue
✗(np.float64(96.0), np.float64(0.0206298828125))This shows that the null hypothesis that the median is negative can be rejected at a confidence level of 5% in favor of the alternative that the median is greater than zero. The p-values above are exact. Using the normal approximation gives very similar values:
res = wilcoxon(d, method='asymptotic')
✓res.statistic, res.pvalue
✗(np.float64(24.0), np.float64(0.04088813291185591))Note that the statistic changed to 96 in the one-sided case (the sum of ranks of positive differences) whereas it is 24 in the two-sided case (the minimum of sum of ranks above and below zero). In the example above, the differences in height between paired plants are provided to `wilcoxon` directly. Alternatively, `wilcoxon` accepts two samples of equal length, calculates the differences between paired elements, then performs the test. Consider the samples ``x`` and ``y``:
import numpy as np x = np.array([0.5, 0.825, 0.375, 0.5]) y = np.array([0.525, 0.775, 0.325, 0.55]) res = wilcoxon(x, y, alternative='greater')✓
res
✗WilcoxonResult(statistic=np.float64(5.0), pvalue=np.float64(0.5625))Note that had we calculated the differences by hand, the test would have produced different results:
d = [-0.025, 0.05, 0.05, -0.05] ref = wilcoxon(d, alternative='greater')✓
ref
✗WilcoxonResult(statistic=np.float64(6.0), pvalue=np.float64(0.5))The substantial difference is due to roundoff error in the results of ``x-y``:
d - (x-y)
✗array([0., 0., 0., 0.])Even though we expected all the elements of ``(x-y)[1:]`` to have the same magnitude ``0.05``, they have slightly different magnitudes in practice, and therefore are assigned different ranks in the test. Before performing the test, consider calculating ``d`` and adjusting it as necessary to ensure that theoretically identically values are not numerically distinct. For example:
d2 = np.around(x - y, decimals=3)
✓wilcoxon(d2, alternative='greater')
✗WilcoxonResult(statistic=np.float64(6.0), pvalue=np.float64(0.5))
See also
- kruskal
- mannwhitneyu
Aliases
scipy.stats.wilcoxon