How to ignore errors in pyzipcode

When trying to convert zip codes to state in a dataframe Code :

from pyzipcode import ZipCodeDatabase

zcdb = ZipCodeDatabase()


df4[‘state’] = df4[‘postal_code’].map(lambda x: zcdb[x].state)

Throws an error

“Couldnt find zipcode : ‘39826’”

Need to ignore this error and move on to the next row

Upvotes: 0

Views: 115

Answers (1)

Sam Morgan
Sam Morgan

Reputation: 3338

There are multiple ways. The older pattern is try/except.

from pyzipcode import ZipCodeDatabase

ZCDB = ZipCodeDatabase()

def get_state(postal_code: int) -> str | None:
    try:
        return ZCDB[x].state
    except KeyError:
        return None

df4[‘state’] = df4[‘postal_code’].map(get_state)

The more modern pattern is to use contextlib.suppress

import contextlib

from pyzipcode import ZipCodeDatabase

ZCDB = ZipCodeDatabase()

def get_state(postal_code: int) -> str | None:
    with contextlib.suppress(KeyError):
        return ZCDB[x].state
    return None


df4[‘state’] = df4[‘postal_code’].map(get_state)

There's also a slightly hacky way, looking the pyzipcode source:

from pyzipcode import ZipCodeDatabase

ZCDB = ZipCodeDatabase()

class FakeZip:
    state = None

default = FakeZip()

df4[‘state’] = df4[‘postal_code’].map(lambda x: ZCDB.get(x, default).state)

Upvotes: 1

Related Questions