[英]pandas: Convert a distance matrix into a dictionary with the elements sorted by proximity
I have the matrix with distance between every point 我有矩阵,每个点之间的距离
Points 1 2 3 .. n
1 0 2.4 1.6 .. 7.8
2 2.4 0 4.9 .. 0.8
3 1.6 4.9 0 .. 2.7
.. .....................
n 7.8 .. .. .. 0
I need obtain the Dictionary with points as key and the list of points as values order by proximity. 我需要获取带有点作为键的字典,并将点列表作为值按接近度排序。
Dictionary:
{
1: [3,2,..,n],
2: [n,..,1,3],
3: [1,n,..,2],
..
}
I should iterate the matrix and order every row and after that insert element in dictionary but exist an elegant way for this. 我应该迭代矩阵并对每一行进行排序,然后在字典中插入元素,但是为此存在一种优雅的方式。
Demo: 演示:
In [79]: d
Out[79]:
1 2 3
1 0.0 2.4 1.6
2 2.4 0.0 4.9
3 1.6 4.9 0.0
DF showing indices / labels of points sorted by proximity (distance to itself - 0'th column has been removed): DF显示按接近度排序的点的索引/标签(距离自身的距离 - 第0列已被删除):
In [80]: pd.DataFrame(np.take(d.columns, np.argsort(d, axis=1).iloc[:, 1:]).T, index=d.index)
Out[80]:
0 1
1 3 2
2 1 3
3 1 2
desired dictionary: 想要的字典:
In [81]: (pd.DataFrame(np.take(d.columns, np.argsort(d, axis=1).iloc[:, 1:]).T, index=d.index)
.T.to_dict('l'))
Out[81]: {1: ['3', '2'], 2: ['1', '3'], 3: ['1', '2']}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.