Convert a distance matrix to a list of pairwise distances in Python [closed]
Asked Answered
H

2

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.

Hydrogenous answered 10/3, 2021 at 21:52 Comment(2)
I'd check out the NumPy and SciPy python libraries: jbencook.com/pairwise-distance-in-numpy. If you provide more details about your problem, I could possibly be of more help.Bassett
Welcome to SO. This isn't a discussion forum or tutorial. Please take the tour and take the time to read How to Ask and the other links found on that page. Invest some time with the Tutorial practicing the examples. It will give you an idea of the tools Python offers to help you solve your problem.Isolate
U
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)
Unreasoning answered 10/3, 2021 at 22:36 Comment(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.Hydrogenous
L
1

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'})
Leaseholder answered 10/3, 2021 at 22:21 Comment(0)
U
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)
Unreasoning answered 10/3, 2021 at 22:36 Comment(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.Hydrogenous

© 2022 - 2024 — McMap. All rights reserved.