Distance Matrix Haversine

2024/11/15 6:50:01

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

             lat       lon
id_zone
0        40.0795  4.338600
1        45.9990  4.829600
2        45.2729  2.882000
3        45.7336  4.850478
4        45.6981  5.043200

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.

def haversine(x):x.lon, x.lat, x.lon2, x.lat2 = map(radians, [x.lon, x.lat, x.lon2, x.lat2])# formule de Haversinedlon = x.lon2 - x.londlat = x.lat2 - x.lata = sin(dlat / 2) ** 2 + cos(x.lat) * cos(x.lat2) * sin(dlon / 2) ** 2c = 2 * atan2(sqrt(a), sqrt(1 - a))km = 6367 * creturn km
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:

             lat       lon
id_zone
0        40.0795  4.338600
1        45.9990  4.829600
2        45.2729  2.882000
3        45.7336  4.850478
4        45.6981  5.043200

And your function is defined as:

def haversine(first, second):# convert decimal degrees to radianslat, lon, lat2, lon2 = map(np.radians, [first[0], first[1], second[0], second[1]])# haversine formuladlon = lon2 - londlat = lat2 - lata = np.sin(dlat/2)**2 + np.cos(lat) * np.cos(lat2) * np.sin(dlon/2)**2c = 2 * np.arcsin(np.sqrt(a))r = 6371 # Radius of earth in kilometers. Use 3956 for milesreturn c * r

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:

# create a matrix for the distances between each pair of zones
distances = np.zeros((len(df), len(df)))
for i in range(len(df)):for j in range(len(df)):distances[i, j] = haversine(df.iloc[i], df.iloc[j])
pd.DataFrame(distances, index=df.index, columns=df.index)

Your output should be similar to this:

id_zone           0           1           2           3           4
id_zone
0          0.000000  659.422944  589.599339  630.083979  627.383858
1        659.422944    0.000000  171.597296   29.555376   37.325316
2        589.599339  171.597296    0.000000  161.731366  174.983855
3        630.083979   29.555376  161.731366    0.000000   15.474533
4        627.383858   37.325316  174.983855   15.474533    0.000000
https://en.xdnf.cn/q/119446.html

Related Q&A

python google geolocation api using wifi mac

Im trying to use Googles API for geolocation giving wifi data to determine location. This is their intro. And this is my code@author: Keith """import requestspayload = {"c…

Python requests and variable payload

Reticulated members,I am attempting to use a GET method that is supported against the endpoint. However, I am using python and wanting to pass the user raw_input that is assigned to a variable:uid = ra…

How should I read and write a configuration file for TkInter?

Ive gathered numbers in a configuration file, and I would like to apply them to buttons. Clicking the button should allow the number to be changed and then re-written to the config file. My current cod…

How to convert this nested dictionary into one single dictionary in Python 3? [duplicate]

This question already has answers here:Convert nested dictionary into a dictionary(2 answers)Flatten nested dictionaries, compressing keys(32 answers)Closed 4 years ago.I have a dictionary like this:a …

How to click unopened tabs where the numbers change

How do I click all the unopened tabs pages where the value changes when you click tabs? (see image below)Take the following script, based off of this question with the following approach:clickMe = wai…

Xlwings / open password protected worksheet in xlsx?

I get an answer how to open a password protected xlsx with xlwings: Xlwings / open password protected xlsx? wb = xlwings.Book("file.xlsx", password="Passw0rd!")But can i also open …

Wrapping an opencv implementaion of an error level analysis algorithm using cython

i have implemented an error level analysis algorithm using c++(opencv version 2.4) and i want to build a python wrapper for it using cython. I have read some part of the documentation of cython for c++…

Setting yticks Location Matplotlib

Im trying to create a plot which has y axis exactly same with this : And Im in this situation and everything is ok until this point:When i try this lines:ax.set_yticks(range(20,67,10)) ax.set_yticklabe…

How to merge list to become string without adding any character in python?

I found that I can join them with -.join(name) but I dont want to add any character. Lets say I have [stanje1, |, st6, , stanje2, |, #] and I want to be like thisstanje1|st6,stanje2|#

Removing a key from a nested dictionary based on value

I previusly asked about adding, and someone helped me out with append. My new problem is trying to delete a key with a nested list, e.g.:JSON:data = {"result":[{"name":"Teddy&q…