Last active
May 1, 2023 21:26
-
-
Save willgeary/c8074268dcda519511bb7394bd797ffb to your computer and use it in GitHub Desktop.
Create a distance matrix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from geopy import distance | |
| import pandas as pd | |
| def make_distance_matrix(coords, addresses): | |
| from_list = [] | |
| to_list = [] | |
| distance_list = [] | |
| for a in list(range(len(coords))): | |
| for b in list(range(len(coords))): | |
| origin_coord = coords[a] | |
| dest_coord = coords[b] | |
| origin_name = addresses[a] | |
| dest_name = addresses[b] | |
| dist = distance.distance(origin_coord, dest_coord).miles | |
| from_list.append(origin_name) | |
| to_list.append(dest_name) | |
| distance_list.append(dist) | |
| # Create a matrix containing the results | |
| distance_matrix = pd.DataFrame() | |
| distance_matrix['from'] = from_list | |
| distance_matrix['to'] = to_list | |
| distance_matrix['distance'] = distance_list | |
| # Do a pivot table | |
| distance_matrix = distance_matrix.pivot_table(values='distance', index='from', columns='to') | |
| return distance_matrix | |
| addresses = [ | |
| 'Address 1', | |
| 'Address 2', | |
| 'Address 3', | |
| 'Address 4', | |
| 'Address 5', | |
| ] | |
| coords = [ | |
| [41.389303, -74.0938969], | |
| [41.4040683, -74.0780502], | |
| [41.4419341, -74.1497553], | |
| [41.4694754, -74.0969499], | |
| [41.4883095, -74.0133781], | |
| ] | |
| make_distance_matrix(coords, addresses) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment