pythoneuclidean-distancedistance-matrix

Convert a distance matrix to a list of pairwise distances in Python


Assume the following distance matrix in python...

  0 1 2 3
0 0 1 4 8
1 1 0 3 7
2 4 3 0 3
3 8 7 3 0

I would like to convert this distance matrix to a list of pairwise euclidean distances, as below...

  Obj1  Obj2  Dist
0  0      1    1
1  0      2    4
2  0      3    8
3  1      2    3
4  1      3    7
5  2      3    3

I cannot seem to find any solution to this, but I am new to python so perhaps I just don't know what to search for. Any help would be much appreciated.


Solution

  • distances = [
        [0, 1, 4, 8],
        [1 ,0, 3, 7],
        [4, 3, 0, 3],
        [8, 7, 3, 0],
    ]
    
    MATRIX_SIZE = len(distances)
    distance_pairs = []
    for i in range(MATRIX_SIZE):
        for j in range(i):
            distance_pairs.append(("distance from {} to {} is {}".format(i, j, distances[i][j])))
    print(distance_pairs)