Skip to content
Advertisement

Distance Matrix Haversine

I am working on a data frame that looks like this :

JavaScript

I’m trying to make a Haverisne distance matrix. Basically for each zone, I would like to calculate the distance between it and all the others in the dataframe. So there should be only 0s on the diagonal. Here is the Haversine function that I use but I can’t make my matrix.

JavaScript

Advertisement

Answer

You can use the solution to this answer Pandas – Creating Difference Matrix from Data Frame

Or in your specific case, where you have a DataFrame like this example:

JavaScript

And your function is defined as:

JavaScript

Where you pass the lat and lon of the first location and the second location.

You can then create a distance matrix using Numpy and then replace the zeros with the distance results from the haversine function:

JavaScript

Your output should be similar to this:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement