Skip to main content
4 of 5
Move description to top for better page preview
Peilonrayz
  • 44.6k
  • 7
  • 80
  • 158

Nearest school to you

I have created a text-based program that finds the nearest school using your coordinates. The CSV DataFrame is available through LimeWire.

I'd like to know how I can improve it.

import geopy # used to get location
from geopy.geocoders import Nominatim
from geopy import distance
import pandas as pd
from pyproj import Transformer
import numpy as np

try: 
    geolocator = Nominatim(user_agent="Everywhere") # name of app
    user_input = input("Enter number and name of street/road ")
    location = geolocator.geocode(user_input)

except AttributeError: # skips
    print('Invalid location')
    print(user_input)

your_location = (location.latitude, location.longitude)

try :
    your_location
except NameError:
    input("Enter number and name of street/road ")

except AttributeError:
    print('Location could not be found')

df = pd.read_csv('longitude_and_latitude.csv', encoding= 'latin1') # encoding makes file readable
t = Transformer.from_crs(crs_from="27700",crs_to="4326", always_xy=True) # instance of transformer class
df['longitude'], df['latitude'] = t.transform((df['Easting'].values), (df['Northing'].values)) # new 

def FindDistance():
    Distance = []
    for lon,lat in zip(df['latitude'],df['longitude']):
        school_cordinates = lon, lat
        distance_apart = distance.distance(school_cordinates, your_location).miles 
        Distance.append(distance_apart)
    return Distance 


df.replace([np.inf, -np.inf], np.nan, inplace=True) # converts infinite vales to Nan
df.dropna(subset=["latitude", "longitude"], how="all", inplace=False) # removes the rows/colums missing values from dataframe
df = df.dropna() # new dataframe

Distance = FindDistance()

df['Distance'] = Distance

schools = df[['EstablishmentName','latitude','longitude','Distance']]

New_order = schools.sort_values(by=["Distance"]) # ascending order
print(New_order)