def nearest_neighbors_kd_tree(x, y, k):
    x, y = map(np.asarray, (x, y))
tree = scipy.spatial.cKDTree(y[:, (None)])
ordered_neighbors = tree.query(x[:, (None)], k)[1]
nearest_neighbor = np.empty((len(x),), dtype=np.intp)
nearest_neighbor.fill(-1)
used_y = set()
for j, neigh_j in enumerate(ordered_neighbors):
    for k in neigh_j:
        if k not in used_y:
            nearest_neighbor[j] = k
used_y.add(k)
break
return nearest_neighbor
finding nearest items across two lists/arrays in Python