Search code examples
pythondictionarymatrixdistanceod

How do I make a dictionary of OD pairs from a distance Matrix using python?


I have a flow matrix from an excel workbook that shows me the movement of cargo between 2 points similar to this:


  1 2 3 ... n
1 0 7 8    
2 5 0 3     .
3 6 9 0     .
.        .  .
.  ...    .
.          .
n           0

I'm trying to create a dictionary where each key consists of each Origin-Destination pair like this:

{(1,1):0; 
 (1,2):7; 
 (1,3):8; 
  ...; 
 (3,2):9; 
 (3,3):0;
  ...;
 (n-1,n-1): x
 (n,n): 0}

Any ideas & help will be highly appreciated!!

What i've done so far is:

import pandas as pd

#Data Commodities#
Kdata= pd.read_excel('turquia.xls', sheet_name = 'Flow')
K = {}
for i in Kdata:
    for j in Kdata:
      K.update({(i,j):Kdata[i]})

I'm getting a dictionary that has the OD pairs but it's inserting all distances in every element:

`

Name: 12, Length: 81, dtype: float64,
 (12,13): 
 0     7115.284948
 1     2356.131379
 2     3077.130525
 3     1994.241678
 4     1374.186546
 ...   
 76     632.489214
 77     845.193097
 78     430.053121
 79    1728.571316
 80    1181.537133

`


Solution

  • It's just a straight forward unstack() to_dict() in pandas

    import pandas as pd
    import io
    df = pd.read_csv(io.StringIO("""id  1 2 3 
    1 0 7 8    
    2 5 0 3
    3 6 9 0"""), sep="\s+").set_index("id")
    
    df.unstack().to_dict()
    

    output

    {('1', 1): 0,
     ('1', 2): 5,
     ('1', 3): 6,
     ('2', 1): 7,
     ('2', 2): 0,
     ('2', 3): 9,
     ('3', 1): 8,
     ('3', 2): 3,
     ('3', 3): 0}