将距离矩阵转换为 Python 中的成对距离列表

时间:2021-03-10 21:52:52

标签: python euclidean-distance distance-matrix

假设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

我想将此距离矩阵转换为成对欧几里得距离列表,如下所示...

  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

我似乎找不到任何解决方案,但我是 python 新手,所以也许我只是不知道要搜索什么。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

您可以使用 Pandas 和 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'})

答案 1 :(得分: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)