Skip to content

scipy/distance-per-pair

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

Calling a distance function once for every pair of points runs Python for each pair. Stack the points into arrays and call cdist or pdist once, which was about 1,000 times faster.

D = np.array([[distance.euclidean(a, b) for b in Y] for a in X])
D = distance.cdist(X, Y, "euclidean")

The rule reports a metric function of scipy.spatial.distance, such as euclidean, cityblock or cosine, called inside a comprehension, a generator or a loop body. On 1,000 by 1,000 points, cdist ran 960 to 2,100 times faster.

xpd check --fix --unsafe-fixes rewrites np.array([[distance.<metric>(a, b) for b in Y] for a in X]) to distance.cdist(X, Y, "<metric>"). Other loop and generator forms remain manual.

This calls $F once per pair of points. Stack the points into arrays and call cdist(XA, XB, '$F') once, or pdist(X, '$F') for the pairs within one array, which ran 960 to 2,100 times faster on 1,000,000 pairs.

See all rules in the SciPy pack.