Using pyzipcodes to create a States column from Zip Code column

1.8k Views Asked by At

I have a dataframe called df1. It includes a zip code column (ie., includes zip codes) and I want to use the pyzipcodes library to create a new column called state, and map the zip codes to states. Does anyone have an idea how to call on and use the pyzipcodes and achieve this task?

I was able to get entries in the state could that look like "ZipCode(zip='85711', city='Tucson', state='AZ'..." but I just want to extract the relevant state with the zip code.

1

There are 1 best solutions below

0
Timeless On

You can use pandas.Series.map to map the column of zipcodes with the ZipCode object (that is basically a dictionnary) created by pyzipcode.

from pyzipcode import ZipCodeDatabase

zcdb = ZipCodeDatabase()

df["state"] = df["zp"].map(lambda x: zcdb[x].state)

Output :

print(df)

      zp state
0  85711    AZ