2

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.

Ben
  • 123
  • 6
  • I'd check out the NumPy and SciPy python libraries: https://jbencook.com/pairwise-distance-in-numpy/. If you provide more details about your problem, I could possibly be of more help. – CobraPi Mar 10 '21 at 22:06
  • Welcome to SO. This isn't a discussion forum or tutorial. Please take the [tour] and take the time to read [ask] and the other links found on that page. Invest some time with [the Tutorial](https://docs.python.org/3/tutorial/index.html) practicing the examples. It will give you an idea of the tools Python offers to help you solve your problem. – wwii Mar 10 '21 at 22:24

2 Answers2

0

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'})
Icarwiz
  • 184
  • 6
0
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)
marke
  • 1,024
  • 7
  • 20
  • 1
    marke, this did exactly what I was looking for! Thank you for the help. My apologies if my question was improperly formatted or structure, I'll take a closer look at the tutorial. – Ben Mar 10 '21 at 23:28