from scipy.spatial import cKDTree as KDTree
import numpy as np
a = np.random.randn(10 ** 8, 3).astype('float32')
k = KDTree(a)
dists, idxs = k.query(a, 2)
thresh_d = 0.1
d_slice = dists[:, (1)]
res = np.flatnonzero(d_slice >= thresh_d)
Speeding up distance between all possible pairs in an array