1

I am geocoding a dataset using the column 'Address'. I would like to either add the string 'N/A' to the row 'lat' when an attribute exception is thrown or simply remove that row if the error is thrown.

Here is what I have tried to make the row with the exception say 'N/A':

try:
    addresses['lat'] = addresses['Address'].apply(addLat)
    addresses['long'] = addresses['Address'].apply(addLong)
except AttributeError:
  addresses['lat'] = 'N/A' # this makes every column say N/A

I have also tried:

try:
    addresses['lat'] = addresses['Address'].apply(addLat)
    addresses['long'] = addresses['Address'].apply(addLong)
except AttributeError:
  addresses['lat'] = 'N/A' # this makes every column say N/A
  pass # this makes the lat column not exists

but the result of this is having no lat/long columns at all.

My question is, how can I access the specific index of the exception and either ignore or insert 'N/A' during an exception?

I have confirmed that the geocode function works on multiple individual rows of the dataset & am certain that my geocoding function is not the issue.

1 Answer 1

2

You want to include your exception handling inside of the apply method. This uses a wrapper function exception_handler to handle exceptions for the inner function:

def exception_handler(func, x):
    try:
        return func(x)
    except AttributeError:
        return 'N/A'
    
addresses['lat'] = addresses['Address'].apply(lambda x: exception_handler(addLat, x))
addresses['long'] = addresses['Address'].apply(lambda x: exception_handler(addLong, x))

Alternatively, you could add the try except block to your addLat and addLong functions.

Sign up to request clarification or add additional context in comments.

Comments

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.