How to display the nearest station with the distance in a database

Question:

The train station dataframe is in this format:

  Station                 Latitude  Longitude 
0 A MRT STATION           1.440585  103.800988
1 B MRT STATION           1.316433  103.882906
2 C MRT STATION           1.369933  103.849558
3 D MRT STATION           1.342501  103.880178    
4 E MRT STATION           1.281874  103.859080

The house dataframe is in this format

   Flat       Latitude  Longitude
0  AA         1.362005  103.853880
1  BB         1.389245  103.876556
2  CC         1.372937  103.870717
3  DD         1.388401  103.771882
4  EE         1.290067  103.829246

i manage to find the closest station to each flat in distance, but how can i include a column which indicates what the closest station is

def compute_distance(flat, place):
Latitude, Longtitude = flat[['Latitude','Longitude']]
min_distance = 9999.0
for place_lat, place_long in zip(place['Latitude'], place['Longitude']):
    distance = geodesic((Latitude, Longtitude), (place_lat, place_long)).m
    if distance < min_distance:
        min_distance = distance
return min_distance
distance_school = flat.apply(compute_distance, axis=1, place=station)

Here is the code that i did to find the shortest distance, but i cant seems to find a way to include the nearest train station

Asked By: N_ote

||

Answers:

How about

def compute_distance(flat, place):
    Latitude, Longtitude = flat[['Latitude','Longitude']]
    min_distance = 9999.0
    nearest_station = None
    for place_lat, place_long, place_name in zip(place['Latitude'], place['Longitude'], place['Station']):
        distance = geodesic((Latitude, Longtitude), (place_lat, place_long)).m
        if distance < min_distance:
            min_distance = distance
            nearest_station = place_name
    return min_distance, nearest_station
Answered By: SystemSigma_
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.