Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - get zipcode from full address

I have a dataframe with full addresses in a column, and I need to create a separate column with just the zip code. Some of the addresses just have the five digit zip code whereas others have the additional four digits.

How do I split the column to just get the zip code?

Example Data

d = {'name':['bob','john'],'address':['123 6th Street,Sterling VA 20165-7513','567 7th Street, Wilmington NC 28411']}
df = pd.DataFrame(d)

I tried using rpartition but I get everything before the zip code:

df['test'] = df['address'].str.rpartition(" ")
print(df)
name    address                                test
bob     123 6th Street,Sterling VA 20165-7513  123 6th Street,Sterling VA
john    567 7th Street, Wilmington NC 28411    567 7th Street, Wilmington NC

This is what I'm trying to get:

name    address                                zipcode
bob     123 6th Street,Sterling VA 20165-7513  20165-7513
john    567 7th Street, Wilmington NC 28411    28411
like image 575
Dread Avatar asked Oct 27 '25 12:10

Dread


2 Answers

Use a regex with str.extract():

df['zip'] = df['address'].str.extract(r'(\d{5}\-?\d{0,4})')

returns:

   name                                address         zip
0   bob  123 6th Street,Sterling VA 20165-7513  20165-7513
1  john    567 7th Street, Wilmington NC 28411       28411

See the pandas page on str.extract() and the python page on re.

In particular, the {5} specifies that we must match 5 repetitions of \d (a numerical digit), while {0,4} indicates that we can match from 0 to 4 repetitions.

like image 99
Brendan Avatar answered Oct 30 '25 02:10

Brendan


You can Try this

df['zip']= [i[-1] for i in df.address.str.split(' ').values]
like image 20
Fouad Selmane Avatar answered Oct 30 '25 01:10

Fouad Selmane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!