Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python pandas:将距离矩阵转换为字典,其中的元素按接近度排序_Python_Pandas_Numpy - Fatal编程技术网

Python pandas:将距离矩阵转换为字典,其中的元素按接近度排序

Python pandas:将距离矩阵转换为字典,其中的元素按接近度排序,python,pandas,numpy,Python,Pandas,Numpy,我有一个矩阵,每个点之间都有距离 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 我需要获得以点为键的字典,以及按接近度排序的以点为值的列表 Dictionary: { 1: [3

我有一个矩阵,每个点之间都有距离

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
我需要获得以点为键的字典,以及按接近度排序的以点为值的列表

Dictionary: 
{
   1: [3,2,..,n],
   2: [n,..,1,3],
   3: [1,n,..,2],
   ..
}
我应该迭代矩阵并对每一行排序,然后在字典中插入元素,但这是一种优雅的方式。

演示:

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显示按接近度排序的点的索引/标签(到自身的距离-第0列已删除):

所需词典:

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']}

如果你有一本字典,你不会没有顺序吗?顺序是字典中的值列表,不是键。我需要对每个关键点按距离排序。
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']}