Skip to content
Advertisement

How to add the name of the nearest point?

I have two data frames with coordinates of attractions and exists.

import pandas as pd
import geopy
from geopy.distance import geodesic
attr = pd.DataFrame(
    {'attraction':['circuit', 'roller coaster'],
    'latitude':[53.35923, 53.35958],
    'longitude':[83.71394, 83.71256]})
exits = pd.DataFrame(
    {'exits':['exit','exit2','exit3', 'exit4'],
    'latitude':[53.35911, 53.3606, 53.35953, 53.3603],
    'longitude':[83.71503, 83.71407, 83.71154, 83.71216]})

  attraction        latitude    longitude
0 circuit           53.35923    83.71394
1 roller coaster    53.35958    83.71256

  exits     latitude    longitude
0 exit      53.35911    83.71503
1 exit2     53.36060    83.71407
2 exit3     53.35953    83.71154
3 exit4     53.36030    83.71216

I use this to get the distance to the nearest exit:

for att in attr.index:
    distances = []
    for ex in exits.index:
        distances.append(geopy.distance.distance(attr.loc[att, 
        ['latitude','longitude']], exits.loc[ex,['latitude','longitude']]))
    min_dist = min(distances)
    attr.loc[att, 'min_distance'] = min_dist

attr

    attraction      latitude    longitude   min_distance
0   circuit         53.35923    83.71394    0.07378947966924111 km
1   roller coaster  53.35958    83.71256    0.06813732373534863 km

I want to add a column with the name of this nearest exit. It has to look like:

    attraction      latitude    longitude   min_distance             name
0   circuit         53.35923    83.71394    0.07378947966924111 km   exit            
1   roller coaster  53.35958    83.71256    0.06813732373534863 km   exit3

I will be grateful for any help!

Advertisement

Answer

attr.loc[att, 'name'] = exits.loc[distances.index(min_dist), 'exits']

Write this line at the end of for loop

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