考虑以下代码,该代码从标记的坐标列表生成距离矩阵:
import numpy as np
import pandas as pd
from scipy.spatial.distance import pdist, squareform
coord_data = [
[1, 2],
[4, 3],
[5, 8],
[6, 7],
]
df = pd.DataFrame(coord_data, index=list('ABCD'))
dist_matrix = squareform(pdist(df, metric='euclidean'))
dist_df = pd.DataFrame(dist_matrix, index=df.index, columns=df.index)
print(dist_df)
A B C D
A 0.000000 3.162278 7.211103 7.071068
B 3.162278 0.000000 5.099020 4.472136
C 7.211103 5.099020 0.000000 1.414214
D 7.071068 4.472136 1.414214 0.000000
是否有一种有效的方法(使用numpy,pandas等)从此距离矩阵中获取N个最小距离对?
例如,如果N = 2,则对于给定的示例,需要类似于以下内容的输出:
[['C', 'D'], ['A', 'B']] # corresponding to minimum distances [1.414214, 3.162278]
这是np.argpartition
用于perf的产品。效率-
def topN_index_columns_from_symmmdist(df, N):
a = dist_df.to_numpy(copy=True)
a[np.tri(len(a), dtype=bool)] = np.inf
idx = np.argpartition(a.ravel(),range(N))[:N]
r,c = np.unravel_index(idx, a.shape)
return list(zip(dist_df.index[r], dist_df.columns[c]))
样品运行-
In [43]: dist_df
Out[43]:
A B C D
A 0.000000 3.162278 7.211103 7.071068
B 3.162278 0.000000 5.099020 4.472136
C 7.211103 5.099020 0.000000 1.414214
D 7.071068 4.472136 1.414214 0.000000
In [44]: topN_index_columns_from_symmmdist(df, N=2)
Out[44]: [('C', 'D'), ('A', 'B')]
In [45]: topN_index_columns_from_symmmdist(df, N=4)
Out[45]: [('C', 'D'), ('A', 'B'), ('B', 'D'), ('B', 'C')]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句