Mathew John
Mathew John

Reputation: 73

creation of distance matrix in python

I am trying to prepare a dijikstra model and i need to prepare a distance list having a dataframe as below:

data={'column1':[1,1,1,1,1,1,1,1,2,2,2,2],'person':['A','A','A','A','B','B','B','B','C','C','C','C'],'location1':['GOA','BANGLORE','GOA','BANGLORE','BANGLORE','DELHI','BANGLORE','DELHII','KOCHI','DELHI','DELHI','KOCHI'],'location2':['BANGLORE','GOA','GOA','BANGLORE','DELHI','DELHI','BANGLORE','BANGLORE','DELHI','KOCHI','DELHI','KOCHI'],'time':[20,40,0,0,34,0,0,23,21,56,0,0]}

df = pd.DataFrame(data)

Needs to create different distance matrix. if column value is 1 and person is A then need to prepare a distance list as [[0,20],[40,0]]. just like that needs the distance matrix on different values in column1 and person.

output:

img

Upvotes: 0

Views: 89

Answers (1)

mozway
mozway

Reputation: 260300

You can use a pivot inside a groupby:

(df.groupby(['column1', 'person'])
   .apply(lambda g: g.pivot('location1', 'location2', 'time').values.tolist())
)

output:

column1  person
1        A         [[0, 40], [20, 0]]
         B         [[0, 34], [23, 0]]
2        C         [[0, 56], [21, 0]]
dtype: object

Upvotes: 1

Related Questions