Skip to content

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)

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 over range(...).

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

  • Reduce once with axis=0, as in np.nanmean(X, axis=0) or np.nanquantile(X, q, axis=0).
  • For group sums, build an indicator matrix G of shape (n_columns, n_groups) with G[j, g] = 1 when column j is in group g, and take np.abs(S @ G).mean(axis=0).
  • For correlations, np.corrcoef(X, y, rowvar=False)[-1, :-1] returns the correlation of every column with y.
  • 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.

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.