Home > Blockchain >  Applying a Function to a List and a Dataframe
Applying a Function to a List and a Dataframe

Time:10-09

I have a single pair of longitude and latitude coordinates that will be inputted into a function to find the distance between it and a second pair of coordinates

For example:

lat_string1 = 48.167
long_string1 = -99.648
lat_string2 = 48.25606
long_string2 = -103.31802 

Using Haversine Distance function I can find the distance between these two coordinates.

def dist(lat1, long1, lat2, long2):

    # convert decimal degrees to radians 
    lat1, long1, lat2, long2 = map(radians, [lat1, long1, lat2, long2])
    # haversine formula 
    dlon = long2 - long1 
    dlat = lat2 - lat1 
    a = sin(dlat/2)**2   cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a)) 
    # Radius of earth in kilometers is 6371
    km = 6371* c
    return km

print(dist(lat_string1, long_string1, lat_string2, long_string2))
272.09670525744474

How do I apply this function to lat_string1 and long_string1 and to coordinates_df containing 1,000's (or three in the example df below) of coordinate pairs so it may print every distance for A, B, and C?

lat_string1 = 48.167
long_string1 = -99.648    
coordinates_df = pd.DataFrame({'Name':['A', 'B', 'C'], 'Longitude':[-102.65324700, -102.75365900, -102.90515700], 'Latitude':[48.47342600, 48.31341700, 48.11112400]})

CodePudding user response:

You could use apply:

coordinates_df['distance'] = coordinates_df.apply(lambda row : dist(lat_string1,long_string1,row['Latitude'],row['Longitude']),axis=1)

Then you can print it.

  • Related