0

I am trying to execute the following function that was published under the same title in StackOverflow. But I get this error that "loop of ufunc does not support argument 0 of type Series which has no callable radians method." I have checked the dtype() of lat and lng in my dataframe and they are both float64 and of the same length. Can you please help me to figure out what I am doing wrong here?

Thanks, MA


def haversine(lat1, lon1, lat2, lon2, to_radians=True, earth_radius=6371):
    if to_radians:
        lat1, lon1, lat2, lon2 = np.radians([lat1, lon1, lat2, lon2])

    a = np.sin((lat2-lat1)/2.0)**2 + \
        np.cos(lat1) * np.cos(lat2) * np.sin((lon2-lon1)/2.0)**2

    return earth_radius * 2 * np.arcsin(np.sqrt(a))

df['dist'] = \
    haversine(df.lat.shift(), df.lng.shift(),
                 df.loc[1:, 'lat'], df.loc[1:, 'lng']) 

Estimating the difference in distance after sorting the dataframe.

Mona
  • 1
  • 1
  • FTR, is this the original question? https://stackoverflow.com/a/40453439/5445670 – Solomon Ucko Apr 06 '23 at 19:12
  • Could you provide a [complete, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) including the versions of Python and all the relevant packages (presumably pandas and numpy) so that we can get a better idea of what might be causing that error for you? – Solomon Ucko Apr 06 '23 at 19:27

1 Answers1

0

Does this fix it?

np.radians(np.array([lat1, lon1, lat2, lon2]))
Solomon Ucko
  • 5,724
  • 3
  • 24
  • 45