繁体   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