user3447653 - 1 year ago 90

Python Question

I have the method below (haversine) that returns the distance between two gps points. Table below is my dataframe.

When I apply the function on the dataframe using, I get the error "cannot convert the series to ". Not sure whether i am missing something. Any help would be appreciated.

`distdf1['distance'] = distdf1.apply(lambda x: haversine(distdf1['SLongitude'], distdf1['SLatitude'], distdf1['ClosestLong'], distdf1['ClosestLat']), axis=1)`

Dataframe:

`SLongitude SLatitude ClosestLong ClosestLat`

0 -100.248093 25.756313 -98.220240 26.189491

1 -77.441536 38.991512 -77.481600 38.748722

2 -72.376370 40.898690 -73.662870 41.025640

Method:

`def haversine(lon1, lat1, lon2, lat2):`

"""

Calculate the great circle distance between two points

on the earth (specified in decimal degrees)

"""

# convert decimal degrees to radians

lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

# haversine formula

dlon = lon2 - lon1

dlat = lat2 - lat1

a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2

c = 2 * asin(sqrt(a))

km = 6367 * c

return km

Answer Source

Try:

```
distdf1.apply(lambda x: haversine(x['SLongitude'], x['SLatitude'], x['ClosestLong'], x['ClosestLat']), axis=1)
```