Skip to content

numpy/builtin-on-array

Pack Severity Fix Versions
NumPy warning unsafe, with xpd check --fix --unsafe-fixes All versions

Python's sum, min, max, sorted and list walk an array one value at a time, which was 37 to 47 times slower. Call the NumPy method instead.

peak = max(np.abs(signal))
peak = np.abs(signal).max(axis=0)

The rule reports sum, min, max, sorted and list around a NumPy call, as in sum(np.abs(a)), or around a comparison with a NumPy call, as in sum(np.abs(a) > 1).

The argument must be a NumPy call that returns one array, or a comparison with such a call. The rule leaves abs and round alone because they already dispatch to NumPy. It also leaves any and all alone because the Python builtins can stop early.

xpd check --fix --unsafe-fixes applies the fixes of this rule. Check the result, because an unsafe fix can change what the code does.

The unsafe fix writes np.abs(a).sum(axis=0), np.abs(a).max(axis=0), np.sort(np.abs(a)) for sorted, which gives an array, and np.abs(a).tolist() for list, which gives Python numbers.

NumPy can sum floating-point values in a different order and propagate NaN in min and max. On a two-dimensional array those methods return one result per column, and tolist() returns rows as lists. np.sort puts NaNs last and sorts each row of a two-dimensional array.

sum walks the array one value at a time in Python. Write $E.sum(axis=0), which ran 37 to 47 times faster on 1,000,000 values.

See all rules in the NumPy pack.