Dafne
Dafne

Reputation: 167

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.

Upvotes: 4

Views: 528

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210852

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):

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

Upvotes: 5

Related Questions