簡體   English   中英

如何計算兩個ZIP之間的距離?

[英]How to calculate Distance between two ZIPs?

我有一個美國郵政編碼列表,並且我必須計算所有郵政編碼點之間的距離。 其6k ZIP長列表,每個實體都有ZIP,城市,州,緯度,長,面積和人口。

因此,我必須計算所有點之間的距離,即: 6000C2組合。

這是我的數據樣本

在此處輸入圖片說明

我已經在SAS中嘗試過此方法,但是它太慢且效率低下,因此我正在尋找使用Python或R的方法。

任何線索將不勝感激。

在SAS中,使用GEODIST函數

GEODIST功能

返回兩個緯度和經度坐標之間的大地距離。

句法

GEODIST(latitude-1, longitude-1, latitude-2, longitude-2 <, options>)

R解決方案

#sample data: first three rows of data provided
df <- data.frame( zip = c( "00501", "00544", "00601" ),
                  longitude = c( -73.045075, -73.045147, -66.750909 ),
                  latitude = c( 40.816799, 40.817225, 18.181189 ),
                  stringsAsFactors = FALSE )

library( sf ) 

#create a spatial data.frame
spdf <- st_as_sf( x = df, 
                  coords = c( "longitude", "latitude"), 
                  crs = "+proj=longlat +datum=WGS84" )

#create the distance matrix (in meters), round to 0 decimals
m <- round( st_distance( spdf ), digits = 0 )

#set row and column names of matrix
colnames( m ) <- df$zip
rownames( m ) <- df$zip

#show distance matrix in meters
m 

# Units: m
#         00501   00544   00601
# 00501       0      48 2580481
# 00544      48       0 2580528
# 00601 2580481 2580528       0

Python解決方案

如果您具有郵政編碼的相應緯度和經度,則可以使用Haversine公式(使用“ mpu”庫)直接計算它們之間的距離,該庫可以確定球面上兩點之間的大圓距離。

示例代碼:

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)

您將得到以公里為單位的合成距離。 輸出:

3.27

PS。 如果您沒有郵政編碼的相應坐標,則可以使用“ uszipcode”庫的“ SearchEngine”模塊獲得相同的坐標(僅適用於美國郵政編碼)

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))

希望這可以幫助!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM