distance matrix using map in python

To create a distance matrix using a list of locations and the geopy library, we can use the following code:

main.py
from geopy.distance import geodesic
import pandas as pd

locations = ['New York, NY', 'Los Angeles, CA', 'Chicago, IL', 'Houston, TX', 'Philadelphia, PA']

# Create a distance matrix with n x n dimensions
n = len(locations)
distance_matrix = [[0] * n for i in range(n)]

# Loop through each location and calculate the distance to every other location
for i in range(n):
    for j in range(i+1, n):
        distance = geodesic(locations[i], locations[j]).km
        distance_matrix[i][j] = distance
        distance_matrix[j][i] = distance

# Print out the distance matrix as a pandas dataframe
df = pd.DataFrame(distance_matrix, columns=locations, index=locations)
print(df)
675 chars
20 lines

The output should be a pandas dataframe that shows the distance (in kilometers) between each pair of locations:

main.py
                  New York, NY  Los Angeles, CA  Chicago, IL  Houston, TX  Philadelphia, PA
New York, NY               0.0       3937.038429  1144.276461  2274.489729        146.613771
Los Angeles, CA         3937.0          0.000000  2802.456632  2042.458239       3748.542080
Chicago, IL             1144.3       2802.456632     0.000000  1268.143098        975.971653
Houston, TX             2274.4       2042.458239  1268.143098     0.000000       2126.270671
Philadelphia, PA         146.6       3748.542080   975.971653  2126.270671          0.000000
557 chars
7 lines

gistlibby LogSnag