Say I have a numpy array A that records the distances from different 1D points. The first column records the coordinate of each destination point, the second column records the pairwise distances. Now I want to construct a distance matrix D that records the pairwise distances (rows correspond to source points, columns correspond to destination points, the distance will be recorded as infinite if unknown). This should be easy, but becomes tricky when there are duplicate destination points. Below is a simple example: I have two points with the coordinate 2.5, and two points with the coordinate 6.1. I tried using np.unique to get the unique columns, but when there are duplicates, it picks the first-appeared distance and lose the distance information of the other pairs import numpy as np A = np.array([[7.3, 0.25], [2.5, 0.32], [3.7, 0.45], [6.1, 0.55], [2.5, 0.91], [4.8, 0.77], [8.6, 0.35], [6.1, 0.82]]) D = np.ones((A.shape[0],A.shape[0])) * np.inf np.fill_diagonal(D, A[:,1]) unq_ids = np.sort(np.unique(A[:,0], return_index=True)[1]) D = D[:,unq_ids] print(D) This gives array([[0.25, inf, inf, inf, inf, inf], [ inf, 0.32, inf, inf, inf, inf], [ inf, inf, 0.45, inf, inf, inf], [ inf, inf, inf, 0.55, inf, inf], [ inf, inf, inf, inf, inf, inf], [ inf, inf, inf, inf, 0.77, inf], [ inf, inf, inf, inf, inf, 0.35], [ inf, inf, inf, inf, inf, inf]]) As you can see, the row 4 and 7 doesn't have any distance information, but I am expecting array([[0.25, inf, inf, inf, inf, inf], [ inf, 0.32, inf, inf, inf, inf], [ inf, inf, 0.45, inf, inf, inf], [ inf, inf, inf, 0.55, inf, inf], [ inf, 0.91, inf, inf, inf, inf], [ inf, inf, inf, inf, 0.77, inf], [ inf, inf, inf, inf, inf, 0.35], [ inf, inf, inf, 0.82, inf, inf]]) In fact, I have a more than 10000 pairs of points, so I want to know a fast way in Numpy to first detect duplicates of the destination points, and then "merge" the distance matrix's columns that correspond to the same destination point (please don't use Pandas). Continue reading...