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)What the rule reports
Section titled “What the rule reports”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,chatterjeexiandweightedtau. - Tests and summaries:
ttest_ind,ttest_rel,mannwhitneyu,ks_2samp,kruskal,f_oneway,levene,shapiro,skew,kurtosis,sem,iqrand the others in the rule, each of which takesaxis=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.
How to fix it
Section titled “How to fix it”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)orkendalltau(X, y[:, None], axis=0).spearmanr(X, y)returns the full correlation matrix, andstatistic[-1, :-1]holds the coefficient of each column withy. - 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.
Diagnostic message
Section titled “Diagnostic message”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.