Search code examples
pythonpandastraveling-salesman

Python and Pandas - Distances with latitude and longitude


I am trying compare distances between points (in this case fake people) in longitudes and latitudes.

I can import the data, then convert the lat and long data to radians and get the following output with pandas:

                   lat      long
name                                
Veronica Session  0.200081  0.246723
Lynne Donahoo     0.775020 -1.437292
Debbie Hanley     0.260559 -1.594263
Lisandra Earls    1.203430 -2.425601
Sybil Leef       -0.029293  0.592702

From there i am trying to compare different points and get the distance between them.

I came across a post that seemed to be of use (https://stackoverflow.com/a/40453439/15001056) but I am unable to get this working for my data set.

Any help in calculating the distance between points would be appreciated. Idealy id like to expand and optimise the route once the distance function is working.


Solution

  • I used the function in the answer you linked and it worked fine. Can't confirm that the distance is in the unit you need though.

    df['dist'] = \
    haversine(df.lat.shift(), df.long.shift(),
                 df.loc[1:, 'lat'], df.loc[1:, 'long'], to_radians=False)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    Veronica Session    0.200081    0.246723    NaN
    Lynne Donahoo       0.775020    -1.437292   9625.250626
    Debbie Hanley       0.260559    -1.594263   3385.893020
    Lisandra Earls      1.203430    -2.425601   6859.234096
    Sybil Leef          -0.029293   0.592702    12515.848878