Convert (origin, destination, distance) to a distance matrix

413 Views Asked by At

I have a matrix with three columns (origin, destination, distance) and I want to convert this to a origin/destination matrix with Pandas, is there a fast way (lambda, map) to do this without for loops?

For example (what I have):

a b 10
a c 20
b c 30

What I need:

   a  b  c
 a 0  10 20
 b 10 0  30
 c 20 30 0
1

There are 1 best solutions below

0
On BEST ANSWER

Here is an option, firstly duplicate the data frame information by concatenating the original data frame values and the origin-destination swapped values and then do a pivot:

pd.DataFrame(pd.np.concatenate([df.values, df.values[:, [1,0,2]]])).pivot(0,1,2).fillna(0)

enter image description here