0

I am trying to use this technique Calculate distance between two coordinates for a fixed point in a DataFrame

   from typing import Tuple
import geopy.distance


def distance(
    lat: float, lon: float, fixed_coords: Tuple[float] = (36.7196, -4.42002)
) -> float:
    return geopy.distance.distance((lat, lon), fixed_coords).km


x = dataframe.apply(lambda row: distance(row[lat], row[lon],axis =1))

error:

---> 11 x = dataframe.apply(lambda row: distance(row[lat], row[lon],axis =1))

NameError: name 'lat' is not defined
4
  • my data set contains "lat" and "lon" as columns. Commented Nov 10, 2022 at 18:38
  • If those are the literal column names then why aren't you passing them as strings? Like row["lat"], row["lon"]? Commented Nov 10, 2022 at 18:40
  • 1
    Yes, but lat and lon need to be in quotes: distance(row['lat'], row['lon'], axis=1) Commented Nov 10, 2022 at 18:41
  • KeyError: 'lat' when using distance(row['lat'], row['lon'], axis=1) Commented Nov 10, 2022 at 18:44

1 Answer 1

0

The name error is becasue the interpreter thinks lat and lon are variable names, not the name of columns. Try using strings instead.

x = dataframe.apply(lambda row: distance(row["lat"], row["lon"],axis =1))
Sign up to request clarification or add additional context in comments.

4 Comments

KeyError: 'lat'
What is the datatype of row? Are you sure that "lat" and "lon" are present in row?
they are column names in the dataframe containing longitude and latitude data as int64
If you are getting a KeyError that means "lat" and "lon" are not keys in the dataframe. You should verify all of the column names are what you expect, I recommend using something like this: stackoverflow.com/questions/49188960/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.