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

Viewed 488

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.

2 Answers

You can use Pandas and DataFrame.stack()

import pandas as pd
import io

txt_dist_mat = '''  0 1 2 3
0 0 1 4 8
1 1 0 3 7
2 4 3 0 3
3 8 7 3 0'''

df = pd.read_fwf(io.StringIO(txt_dist_mat), index_col=0)

euc_mat = df.stack().reset_index().rename(columns={'level_0': 'Obj1', 'level_1': 'Obj2', 0: 'Dist'})
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)
Related