calculate distance between latitude longitude columns for pandas data frame

Question:

I am trying to apply this code:

import h3

coords_1 = (52.2296756, 21.0122287)
coords_2 = (52.406374, 16.9251681)
distance = h3.point_dist(coords_1, coords_2, unit='km')
distance

to a pandas dataframe. This is my not working attempt.

data = {'lat1':[52.2296756],
        'long1':[21.0122287],
        'lat2':[52.406374],
        'long2':[16.9251681],      
}
df = pd.DataFrame(data)
df

df['distance'] = = h3.point_dist((df['lat1'], df['long1']), (df['lat2'], df['long2']), unit='km')

Any help would be very much appreciated. Thanks!

Asked By: cs0815

||

Answers:

It’s working you need to just delete the second "="

data = {'lat1':[52.2296756],
        'long1':[21.0122287],
        'lat2':[52.406374],
        'long2':[16.9251681],      
}
df = pd.DataFrame(data)
df

df['distance'] =  h3.point_dist((df['lat1'], df['long1']), (df['lat2'], df['long2']), unit='km')

result

Answered By: Ran A

Assuming you have more than a single row for which you would like to compute the distance you can use apply as follows:

df['Dist'] = df.apply(lambda row: h3.point_dist((row['lat1'], row['long1']), (row['lat2'], row['long2'])), axis=1)

Which will add a column to your dataframe simi9lar to the following:

      lat1        long1      lat2       long2        Dist
0   52.229676   21.012229   52.406374   16.925168   2.796556
1   57.229676   30.001176   48.421365   17.256314   6.565542 

Please note, my distance calculations may not agree with yours, since I used a dummy function for h3.point_dist computation

Answered By: itprorh66
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.