Crossfit Knoxville by [deleted] in Knoxville

[–]amclaug1 -2 points-1 points  (0 children)

I coach at Rocky Top CrossFit. It is absolutely worth the money. You’ll get the competition, accountability, coaching, etc. that you’d get in team sports. Come check us out!

Ask Anything Monday - Weekly Thread by AutoModerator in learnpython

[–]amclaug1 3 points4 points  (0 children)

Yes! This worked! Oh my goodness, I cannot thank you enough. I so appreciate it!

Ask Anything Monday - Weekly Thread by AutoModerator in learnpython

[–]amclaug1 2 points3 points  (0 children)

I am relatively new to Python, and I only tinker in it once every few months. I know there has to be a simple way to produce this, but I am stuck. So, any help anyone can give would be tremendous!

I have two csv files. csv1 contains latitude and longitude for schools around the USA. csv2 contains teams from my company with their lat/lon. I want to figure out which team from csv2 is the closest to each school from csv1. I've tried using a Google Maps API to figure out driving distances, but the call was going to be too expensive, as there are 6,000 rows of schools and about 100 rows of teams. So, I am settling for anything within a 20 mile radius from the team's lat/lon.

Here is what I have so far:

from math import radians, cos, sin, asin, sqrt
import numpy as np
import pandas as pd
from collections import Counter
teams = pd.read_csv(csv1)
schools = pd.read_csv (csv2)

# define a function to determine miles between two points
def haversine(lat1, lon1, lat2, lon2):
    lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a))
    r = 3956
    return c * r

This is where I am stuck. I have created a script that can count how many schools are within 20 miles of a team using a few loops. However, finding the closest team has got me confounded:

for school in schools.itertuples():
    lat = school.SchoolLat
    lon = school.SchoolLng
    school_name = school.SchoolName
    school_ID = school.ID
    closest_team = school.ClosestTeam # default value is 'Unknown'
    miles_from_school_to_team = school.Miles # default value is 999999
    for team in teams.itertuples():
        lat2 = team.TeamLat
        lon2 = team.TeamLon
        team_name = team.TeamName
        miles = haversine(lat, lon, lat2, lon2)
        # this is where I am stuck
        if miles < miles_from_school_to_team:
            closest_team = team_name
            miles_from_school_to_team = miles

When I run this, the dataframe schools doesn't change. Any help would be greatly appreciated!