I have two data frames with coordinates of attractions and exists.
JavaScript
x
22
22
1
import pandas as pd
2
import geopy
3
from geopy.distance import geodesic
4
attr = pd.DataFrame(
5
{'attraction':['circuit', 'roller coaster'],
6
'latitude':[53.35923, 53.35958],
7
'longitude':[83.71394, 83.71256]})
8
exits = pd.DataFrame(
9
{'exits':['exit','exit2','exit3', 'exit4'],
10
'latitude':[53.35911, 53.3606, 53.35953, 53.3603],
11
'longitude':[83.71503, 83.71407, 83.71154, 83.71216]})
12
13
attraction latitude longitude
14
0 circuit 53.35923 83.71394
15
1 roller coaster 53.35958 83.71256
16
17
exits latitude longitude
18
0 exit 53.35911 83.71503
19
1 exit2 53.36060 83.71407
20
2 exit3 53.35953 83.71154
21
3 exit4 53.36030 83.71216
22
I use this to get the distance to the nearest exit:
JavaScript
1
14
14
1
for att in attr.index:
2
distances = []
3
for ex in exits.index:
4
distances.append(geopy.distance.distance(attr.loc[att,
5
['latitude','longitude']], exits.loc[ex,['latitude','longitude']]))
6
min_dist = min(distances)
7
attr.loc[att, 'min_distance'] = min_dist
8
9
attr
10
11
attraction latitude longitude min_distance
12
0 circuit 53.35923 83.71394 0.07378947966924111 km
13
1 roller coaster 53.35958 83.71256 0.06813732373534863 km
14
I want to add a column with the name of this nearest exit. It has to look like:
JavaScript
1
4
1
attraction latitude longitude min_distance name
2
0 circuit 53.35923 83.71394 0.07378947966924111 km exit
3
1 roller coaster 53.35958 83.71256 0.06813732373534863 km exit3
4
I will be grateful for any help!
Advertisement
Answer
JavaScript
1
2
1
attr.loc[att, 'name'] = exits.loc[distances.index(min_dist), 'exits']
2
Write this line at the end of for loop