Reputation: 366
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 |
Upvotes: 1
Views: 1463
Reputation: 1
from django.contrib.gis.geos import Point
#Current Location (longitude , latitude )
current_coord = Point(-3.993046, 40.410323 )
#Target Location (longitude , latitude )
target_coord = Point(1.696572, 41.490604 )
#Calculate distance in kilometer
distance = current_coord.distance(target_coord) * 100
Upvotes: 0
Reputation: 56
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))
Upvotes: 2
Reputation: 645
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
)
Upvotes: 0