numpy/axis-reduce-loop
| Pack | Severity | Fix | Versions |
|---|---|---|---|
| NumPy | warning | none, edit by hand | All versions |
A loop or comprehension that reduces one column of an array per pass calls NumPy once for every column. Every NumPy reduction takes axis=0 and returns one value per column in one call.
importance = []for j, name in enumerate(features): importance.append(np.mean(np.abs(shap_values[:, j])))importance = np.abs(shap_values).mean(axis=0)What the rule reports
Section titled “What the rule reports”The rule reports a NumPy reduction, such as np.mean, np.nanmean, np.std, np.quantile or np.ptp, or the same method on a slice, when its argument is the column X[:, j] and j is the name of the enclosing for loop or comprehension. It leaves a reduction alone that already passes axis=, or that sits in an if test that guards the rest of the pass. It also reports:
- Column-group sums:
S[:, idx].sum(axis=1)in a loop over groups of column indices. - Correlation per column:
np.corrcoef(X[:, j], y)in a loop over columns. - Norm per row:
np.linalg.norm(X[i] - c)in a loop overrange(...).
How to fix it
Section titled “How to fix it”xpd has no automatic fix, so make the change by hand.
- Reduce once with
axis=0, as innp.nanmean(X, axis=0)ornp.nanquantile(X, q, axis=0). - For group sums, build an indicator matrix
Gof shape(n_columns, n_groups)withG[j, g] = 1when columnjis in groupg, and takenp.abs(S @ G).mean(axis=0). - For correlations,
np.corrcoef(X, y, rowvar=False)[-1, :-1]returns the correlation of every column withy. - For row norms,
np.linalg.norm(X - c, axis=1).
On NumPy 2.5.4 each of these gave the same values as the loop.
Diagnostic message
Section titled “Diagnostic message”This reduces one column $J of $A per pass. Reduce every column in one call with axis=0, as in np.$F($A, axis=0) or np.abs($A).mean(axis=0), which returns one value per column.See all rules in the NumPy pack.