Zed Fang
Zed Fang

Reputation: 883

Could I use python to retrieve a number of zip code within a radius

picture: retrieve a number of zip code within a radius in excel

As you can see on the picture above, I use excel to expand the target zip code (a list of zip code I randomly type in). And then I can get a list of expanded zip code within a 35 miles radius (it can be 10 mils, 50 miles, depending on what I want to look at) of my target zip code.

However, the process takes a really long time, especially if I have different groups of target zip code to expand. I am thinking whether there is more efficient way in python instead.

I know geopy can help me get the distance between 2 zip code, but it cannot give a list of zip within a location.

Upvotes: 2

Views: 7995

Answers (1)

G4mo
G4mo

Reputation: 607

For USA zip codes, there is pyzipcode package.

Single zip code query:

from pyzipcode import ZipCodeDatabase
zcdb = ZipCodeDatabase()
in_radius = [z.zip for z in zcdb.get_zipcodes_around_radius('55001', 8)] # ('ZIP', radius in miles)
radius_utf = [x.encode('UTF-8') for x in in_radius] # unicode list to utf list

Output:

>>> in_radius
[u'54016', u'54021', u'55001', u'55003', u'55042', u'55043', u'55082', u'55129']
>>> radius_utf
['54016', '54021', '55001', '55003', '55042', '55043', '55082', '55129']

Multiple zip codes at once:

from pyzipcode import ZipCodeDatabase
zcdb = ZipCodeDatabase()
input_zips = []
input_zips = raw_input("Enter zip codes (separated by comma): ").replace(" ", "").split(",") # Remove whitespace and split by comma to list
input_radius = raw_input("Enter radius from entered zip code (in miles): ") # In Python 3.x change both raw_input() to input()
for y in range(0, len(input_zips)): # Loop to find and print radius lists
    in_radius = [z.zip for z in zcdb.get_zipcodes_around_radius(input_zips[y], input_radius)] # ('ZIP', radius in miles)
    radius_utf = map(int, [x.encode('UTF-8') for x in in_radius]) # Unicode list to UTF list and map to convert str list to int list
    print("Target zip: %s, Radius %s miles, List of zip codes in radius:\n%s\n" %(input_zips[y], input_radius, radius_utf))

Output:

Enter zip codes (separated by comma): 54021, 55001
Enter radius from entered zip code (in miles): 10
Target zip: 54021, Radius 10 miles, List of zip codes in radius:
[54021, 55001, 55033, 55043, 55089, 55129]

Target zip: 55001, Radius 10 miles, List of zip codes in radius:
[54016, 54021, 54082, 55001, 55003, 55016, 55033, 55042, 55043, 55082, 55090, 55115, 55125, 55129]

Upvotes: 4

Related Questions