Skip to content

scipy/stats-in-column-loop

Pack Severity Fix Versions
SciPy warning none, edit by hand All versions

A loop or comprehension that calls a SciPy statistic on one column per pass runs the test once for every column. These functions take axis= and return one statistic and p-value per column in one call.

pvalues = {col: ttest_ind(a[col], b[col]).pvalue for col in features}
pvalues = pd.Series(ttest_ind(a[features], b[features], axis=0, nan_policy="omit").pvalue, index=features)

The rule reports a call to a scipy.stats function whose argument is one column selected by the loop name, as X[:, j], df.iloc[:, j] or df[col]. df[col] counts only when the loop runs over column names, such as df.columns or a list whose name holds col, feat, var or name. It reports:

  • Correlations: pearsonr, spearmanr, kendalltau, pointbiserialr, chatterjeexi and weightedtau.
  • Tests and summaries: ttest_ind, ttest_rel, mannwhitneyu, ks_2samp, kruskal, f_oneway, levene, shapiro, skew, kurtosis, sem, iqr and the others in the rule, each of which takes axis= on SciPy 1.18.1.

A loop over pairs from another iterable, such as (train, test) folds, is left alone, because those names select rows.

xpd has no automatic fix, so make the change by hand.

  • For coefficients only, df.corrwith(y, method="pearson"), "spearman" or "kendall".
  • For p-values, pass the 2-D array once with the target broadcast, as in pearsonr(X, y[:, None], axis=0) or kendalltau(X, y[:, None], axis=0). spearmanr(X, y) returns the full correlation matrix, and statistic[-1, :-1] holds the coefficient of each column with y.
  • For tests, ttest_ind(A, B, axis=0, nan_policy="omit").

On SciPy 1.18.1 the broadcast forms gave the same statistics and p-values as the loop. somersd and anderson_ksamp take no axis= and are not reported.

This calls $F once per pass of the loop over $C, on one column at a time. Correlate every column in one call. df.corrwith(y, method="pearson", "spearman" or "kendall") returns the coefficients, and for p-values pass the 2-D array once with the target broadcast, as in pearsonr(X, y[:, None], axis=0), or take spearmanr(X, y).statistic[-1, :-1].

See all rules in the SciPy pack.