'Calculating distance between Multiple Locations

I have 2 files contractor.csv, locations.csv.

Within the contractor.csv there is a longitude column, a latitude column, and a distance_pref Within the locations.csv there is a longitude column, a latitude column, along with the name

I am trying to calculate the distance between all points inside the contractor.csv and the locations.csv and in a new column inside of constractor.csv have a list of all the location names that reside within their distance preference.

Below is the code I have but it is a bit hacky

import pandas as pd
from geopy import distance


contractor_df = pd.read_csv('contractor.csv')
location_df = pd.read_csv('location.csv')

contractor_df['cords'] = list(zip(contractor_df['Latitude'], contractor_df['Longitude']))
location_df['cords'] = list(zip(location_df['Lat'], location_df['Long']))


def calc_distance(cords1, cords2):
    distance_to = distance.distance(cords1, cords2).miles
    return distance_to


for contractor_index, contractor_row in contractor_df.iterrows():
    for location_index, location_row in location_df.iterrows():
        my_val = calc_distance2(location_row.cords, contractor_row.cords)
        if my_val <= contractor_df.loc[contractor_index, 'Distance_Pref']:
            contractor_df['assignment'] = contractor_df['assignment'].astype(str)
            contractor_df.loc[contractor_index, 'assignment'] += f", {location_row.name}"

While this works, is there a better solution that could be done using pandas functions.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source