問題描述
我有一個美國郵政編碼列表,我必須計算所有郵政編碼點之間的距離.它是一個 6k 長的 ZIP 列表,每個實體都有 ZIP、City、State、Lat、Long、Area 和 Population.
I have a list of US ZIP codes and I have to calculate distance between all the ZIP Code Points. Its a 6k ZIPs long list, each entity has ZIP, City, State, Lat, Long, Area and Population.
所以,我必須計算所有點之間的距離,即;6000C2組合.
So, I have to calculate distance between all the points, ie; 6000C2 combinations.
這是我的數據示例
我已經在 SAS 中嘗試過,但它太慢且效率低下,因此我正在尋找一種使用 Python 或 R 的方法.
I've tried this in SAS but its too slow and inefficient, hence I'm looking for a way using Python or R.
任何線索將不勝感激.
推薦答案
Python解決方案
如果您有郵政編碼對應的緯度和經度,您可以通過使用'mpu'庫的Haversine公式直接計算它們之間的距離,該庫確定球體上兩點之間的大圓距離.
If you have the corresponding latitudes and longitudes for the Zip codes, you can directly calculate the distance between them by using Haversine formula using 'mpu' library which determines the great-circle distance between two points on a sphere.
示例代碼:
import mpu
zip_00501 =(40.817923,-73.045317)
zip_00544 =(40.788827,-73.039405)
dist =round(mpu.haversine_distance(zip_00501,zip_00544),2)
print(dist)
您將獲得以公里為單位的合成距離.輸出:
You will get the resultant distance in kms. Output:
3.27
PS.如果您沒有相應的郵政編碼坐標,您可以使用uszipcode"庫的SearchEngine"模塊獲得相同的坐標(僅適用于美國郵政編碼)
PS. If you don't have the corresponding coordinates for the zip codes, you can get the same using 'SearchEngine' module of 'uszipcode' library (only for US zip codes)
from uszipcode import SearchEngine
#for extensive list of zipcodes, set simple_zipcode =False
search = SearchEngine(simple_zipcode=True)
zip1 = search.by_zipcode('92708')
lat1 =zip1.lat
long1 =zip1.lng
zip2 =search.by_zipcode('53404')
lat2 =zip2.lat
long2 =zip2.lng
mpu.haversine_distance((lat1,long1),(lat2,long2))
希望這會有所幫助!
這篇關于如何計算兩個 ZIP 之間的距離?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!