-1

I have a dataset as follows;

     Group  Zip 
      1     30079
      1     30059
      1     30049
      1     30024
      2     30061
      2     30031
      2     30043
      2     30130

Within each group, is there a way to calculate the distance between each successive zip using ZIP CODE alone.

Is there a formula I can use for this?

tj judge
  • 626
  • 3
  • 17
  • 2
    How do you define distance between zip codes? – BigBen Sep 02 '21 at 18:50
  • 1
    There is not a formula, but there is an API. I use one from Bing and if you use a zip code it uses the center of the zip code. – Martin Sep 02 '21 at 18:51
  • Does this answer your question? [Lookup City and State by Zip Google Geocode Api](https://stackoverflow.com/questions/4749706/lookup-city-and-state-by-zip-google-geocode-api) – ti7 Sep 02 '21 at 18:55
  • practically, you will need to decide how you define distance (the center seems most likely, but you may find the edge makes sense for your task!), then you will either need a lookup table or API (of which there are many, such as Google's Geocode) to discover the relative position (as a lat/lon) or directly get the distance (which could be different for roads vs direct vs naive haversine, etc.) – ti7 Sep 02 '21 at 18:58

2 Answers2

1

I would try the geopy package:

I stole these examples from the blog post linked below: 

from geopy.geocoders import Nominatim
geocoder = Nominatim(user_agent = 'your_app_name')

# after initiating geocoder
location = geocode(address)
# returns location object with longitude, latitude and altitude instances
(location.latitude, location.longitude)

from geopy.distance import geodesic
distance_in_miles = geodesic(coordinate1, coordinate2).miles

Links for reference: https://pypi.org/project/geopy/

https://towardsdatascience.com/things-to-do-with-latitude-longitude-data-using-geopy-python-1d356ed1ae30

SquatLicense
  • 188
  • 8
  • can you add a little example about _how_ they would use this? links suffer from rot and are [otherwise problematic](https://meta.stackexchange.com/questions/225370/your-answer-is-in-another-castle-when-is-an-answer-not-an-answer) – ti7 Sep 02 '21 at 19:23
  • 1
    I see, good point. I'll replace links with examples. – SquatLicense Sep 02 '21 at 19:43
0

Super simple (although you have to get a free key first):

import requests
import json

location1 = 48161
location2 = 22030
zipcodekey = 'your key here'

 url = f'https://www.zipcodeapi.com/rest/{zipcodekey}/distance.json/{location1}/{location2}/mile'

response = requests.get(url)
print (response.text)

This outputs:

'{"distance":386.075}'

Finally, if you want:

result = json.loads(response.text)
print f'The distance is {result["distance"]}'
Martin
  • 1,095
  • 9
  • 14