【发布时间】:2019-12-08 04:16:27
【问题描述】:
我有两个要循环的数据帧,应用一个 Haversine 函数,并在一个新数组中构造结果。我想获取 da_store 中第一家餐厅的 lat、lng 坐标,对 da_univ 的所有 lat、lng 应用 Haversine 函数,存储结果并获取最小值。最终,为每个商店计算所有 da_univ 坐标的欧几里得距离,并找到最近的大学和学院。
到目前为止,这是我对嵌套 for 循环的尝试,我正在努力以正确的格式保存结果并找到最小值。
for index_store, row_store in da_store.iterrows():
store_lat = row_store['lat']
store_lon = row_store['lon']
store_list = []
for index_univ, row_univ in da_univ.iterrows():
univ_lat = row_univ['LATITUDE']
univ_lon = row_univ['LONGITUDE']
distance = haversine_np(store_lon, store_lat, univ_lon, univ_lat)
print(distance)
数据框 1:da_store
In [203]: da_store.head()
Out[203]:
Restaurant # Restaurant Name Address City State Zip Code lat lon
0 3006 Weymouth Dual Riverway Plaza, Weymouth, MA Weymouth MA 2191 42.244559 -70.936438
1 3009 Somerset Dual Somerset Plaza, Rt. 6, Somerset, MA Somerset MA 2725 41.734643 -71.152320
2 3502 Westboro Mass Pike West Mile Post 105; Mass Turnpike W., Westboro, MA Westboro MA 1581 42.253973 -71.663506
3 3503 Charlton Mass Pike East Mile Post 81; Mass Turnpike E., Charlton, MA Charlton MA 1507 42.101589 -72.018530
4 3504 Charlton Mass Pike West Mile Post 89; Mass Turnpike W., Charlton City, MA Charlton City MA 1508 42.101497 -72.018247
数据框 2:da_univ
In [204]: da_univ.head()
Out[204]:
INSTNM ZIP CITY STABBR LATITUDE LONGITUDE
0 Hult International Business School 02141-1805 Cambridge MA 42.369968 -71.070645
1 New England College of Business and Finance 2110 Boston MA 42.353619 -71.056671
2 Assumption College 01609-1296 Worcester MA 42.294226 -71.828991
3 Bancroft School of Massage Therapy 1604 Worcester MA 42.268973 -71.778113
4 Bay State College 2116 Boston MA 42.351760 -71.076991
Haversine 函数:haversine_np
from math import radians, cos, sin, asin, sqrt
def haversine_np(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
All args must be of equal length.
"""
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2
c = 2 * np.arcsin(np.sqrt(a))
km = 6367 * c
return km
我需要练习我的基本编程谢谢你的帮助!
【问题讨论】:
-
如果您使用的是
np.cos、np.sin、np.sqrt和np.radians,那么您可以删除from math import ...,因为您没有使用这些功能。