Home > front end >  Calculate distance between two coordinates for a fixed point in a DataFrame
Calculate distance between two coordinates for a fixed point in a DataFrame

Time:07-13

I have the following DataFrame in pandas:

code latitude longitude
01 40.410323 -3.993046
02 41.490604 1.696572
03 39.287817 -0.435448
04 38.594316 -0.128489
05 36.900799 -3.423063
06 36.541667 -4.625

I want to create a new column called km_to_fixed_coords in which the distance in coordinates to a new fixed point is calculated, which will be the same for all rows (36.7196, -4.42002).

This code calculates the distance between two coordinates in kilometres.

import geopy.distance
# (latitude, longitude)
coords_1 = (x, y)
fixed_coords = (36.7196, -4.42002)

print(geopy.distance.distance(coords_1, fixed_coords).km)

The resulting DataFrame should look like the example:

code latitude longitude km_to_fixed_coords
01 40.410323 -3.993046 411.3819700981563
02 41.490604 1.696572 748.2482442578678
03 39.287817 -0.435448 451.2806740048897
04 38.594316 -0.128489 432.0145327165797
05 36.900799 -3.423063 91.20470627900332
06 36.541667 -4.625342 26.96511660526825

CodePudding user response:

from typing import Tuple
import geopy.distance


def distance(
    lat: float, lon: float, fixed_coords: Tuple[float] = (36.7196, -4.42002)
) -> float:
    return geopy.distance.distance((lat, lon), fixed_coords).km


df["km_to_fixed_coords"] = df.apply(lambda row: distance(row.latitude, row.longitude))

CodePudding user response:

apply a method on rows like this ?

import geopy.distance

# (latitude, longitude)
fixed_coords = (36.7196, -4.42002)

df['km_to_fixed_coords'] = df.apply(
    lambda row: geopy.distance.distance((row.latitude, row.longitude), fixed_coords).km,
    axis=1
)
  • Related