bundles / scipy latest / scipy / stats / _stats_py / ttest_ind
function
scipy.stats._stats_py:ttest_ind
source: /scipy/stats/_stats_py.py :6464
Signature
def ttest_ind ( a , b , * , axis = 0 , equal_var = True , nan_policy = propagate , alternative = two-sided , trim = 0 , method = None , keepdims = False ) Summary
Calculate the T-test for the means of two independent samples of scores.
Extended Summary
This is a test for the null hypothesis that 2 independent samples have identical average (expected) values. This test assumes that the populations have identical variances by default.
Parameters
a, b: array_likeThe arrays must have the same shape, except in the dimension corresponding to
axis(the first, by default).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.equal_var: bool, optionalIf True (default), perform a standard independent 2 sample test that assumes equal population variances [1]. If False, perform Welch's t-test, which does not assume equal population variance [2].
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.
alternative: {'two-sided', 'less', 'greater'}, optionalDefines the alternative hypothesis. The following options are available (default is 'two-sided'):
'two-sided': the means of the distributions underlying the samples are unequal.
'less': the mean of the distribution underlying the first sample is less than the mean of the distribution underlying the second sample.
'greater': the mean of the distribution underlying the first sample is greater than the mean of the distribution underlying the second sample.
trim: float, optionalIf nonzero, performs a trimmed (Yuen's) t-test. Defines the fraction of elements to be trimmed from each end of the input samples. If 0 (default), no elements will be trimmed from either side. The number of trimmed elements from each tail is the floor of the trim times the number of elements. Valid range is [0, .5).
method: ResamplingMethod, optionalDefines the method used to compute the p-value. If
methodis an instance of PermutationMethod/MonteCarloMethod, the p-value is computed using scipy.stats.permutation_test/scipy.stats.monte_carlo_test with the provided configuration options and other appropriate settings. Otherwise, the p-value is computed by comparing the test statistic against a theoretical t-distribution.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: `~scipy.stats._result_classes.TtestResult`An object with the following attributes:
statistic
statistic
pvalue
pvalue
df
df
The object also has the following method:
confidence_interval(confidence_level=0.95)
Computes a confidence interval around the difference in population means for the given confidence level. The confidence interval is returned in a
namedtuplewith fieldslowandhigh.
Notes
Suppose we observe two independent samples, e.g. flower petal lengths, and we are considering whether the two samples were drawn from the same population (e.g. the same species of flower or two species with similar petal characteristics) or two different populations.
The t-test quantifies the difference between the arithmetic means of the two samples. The p-value quantifies the probability of observing as or more extreme values assuming the null hypothesis, that the samples are drawn from populations with the same population means, is true. A p-value larger than a chosen threshold (e.g. 5% or 1%) indicates that our observation is not so unlikely to have occurred by chance. Therefore, we do not reject the null hypothesis of equal population means. If the p-value is smaller than our threshold, then we have evidence against the null hypothesis of equal population means.
By default, the p-value is determined by comparing the t-statistic of the observed data against a theoretical t-distribution.
It is also possible to compute the test statistic using a permutation test by passing method=scipy.stats.PermutationMethod(n_resamples=permutations), where permutations is the desired number of "permutations" to use in forming the null distribution. When 1 < permutations < binom(n, k), where
kis the number of observations ina,nis the total number of observations inaandb, andbinom(n, k)is the binomial coefficient (nchoosek),
the data are pooled (concatenated), randomly assigned to either group a or b, and the t-statistic is calculated. This process is performed repeatedly (permutations times), generating a distribution of the t-statistic under the null hypothesis, and the t-statistic of the observed data is compared to this distribution to determine the p-value. Specifically, the p-value reported is the "achieved significance level" (ASL) as defined in 4.4 of [3]. Note that there are other ways of estimating p-values using randomized permutation tests; for other options, see the more general permutation_test.
When permutations >= binom(n, k), an exact test is performed: the data are partitioned between the groups in each distinct way exactly once.
The permutation test can be computationally expensive and not necessarily more accurate than the analytical test, but it does not make strong assumptions about the shape of the underlying distribution.
Use of trimming is commonly referred to as the trimmed t-test. At times called Yuen's t-test, this is an extension of Welch's t-test, with the difference being the use of winsorized means in calculation of the variance and the trimmed sample size in calculation of the statistic. Trimming is recommended if the underlying distribution is long-tailed or contaminated with outliers [4].
The statistic is calculated as (np.mean(a) - np.mean(b))/se, where se is the standard error. Therefore, the statistic will be positive when the sample mean of a is greater than the sample mean of b and negative when the sample mean of a is less than the sample mean of b.
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.
Array API Standard Support
ttest_ind has experimental support for Python Array API Standard compatible backends in addition to NumPy. Please consider testing these features by setting an environment variable SCIPY_ARRAY_API=1 and providing CuPy, PyTorch, JAX, or Dask arrays as array arguments. The following combinations of backend and device (or other capability) are supported.
==================== ==================== ==================== Library CPU GPU ==================== ==================== ==================== NumPy ✅ n/a CuPy n/a ✅ PyTorch ✅ ⛔ JAX ✅ ✅ Dask ✅ n/a ==================== ==================== ====================
See
dev-arrayapifor more information.
Examples
import numpy as np from scipy import stats rng = np.random.default_rng()✓
rvs1 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng) rvs2 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)✓
stats.ttest_ind(rvs1, rvs2) stats.ttest_ind(rvs1, rvs2, equal_var=False)✗
rvs3 = stats.norm.rvs(loc=5, scale=20, size=500, random_state=rng)
✓stats.ttest_ind(rvs1, rvs3) stats.ttest_ind(rvs1, rvs3, equal_var=False)✗
rvs4 = stats.norm.rvs(loc=5, scale=20, size=100, random_state=rng)
✓stats.ttest_ind(rvs1, rvs4) stats.ttest_ind(rvs1, rvs4, equal_var=False)✗
rvs5 = stats.norm.rvs(loc=8, scale=20, size=100, random_state=rng)
✓stats.ttest_ind(rvs1, rvs5) stats.ttest_ind(rvs1, rvs5, equal_var=False)✗
a = (56, 128.6, 12, 123.8, 64.34, 78, 763.3) b = (1.1, 2.9, 4.2)✓
stats.ttest_ind(a, b, trim=.2)
✗Aliases
-
scipy.stats.ttest_ind