我有两个要遍历的dataFrame,应用Haversine函数,并在新数组中构造结果。我想获取da_store中第一家餐厅的经度,纬度坐标,对所有的经纬度的纬度,经度应用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


我需要练习我的基本编程,谢谢您的帮助!

最佳答案

如果对pandas和numpy使用loop,则很可能您做错了。学习并应用这些库提供的矢量化功能:

# Build an index that contain every pairing of Store - University
idx = pd.MultiIndex.from_product([da_store.index, da_univ.index], names=['Store', 'Univ'])

# Pull the coordinates of the store and the universities together
# We don't need their name here
df = pd.DataFrame(index=idx) \
        .join(da_store[['lat', 'lon']], on='Store') \
        .join(da_univ[['LATITUDE', 'LONGITUDE']], on='Univ')


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

df['Distance'] = haversine_np(*df[['lat', 'lon', 'LATITUDE', 'LONGITUDE']].values.T)

# The closest university to each store
min_distance = df.loc[df.groupby('Store')['Distance'].idxmin(), 'Distance']

# Pulling everything together
min_distance.to_frame().join(da_store, on='Store').join(da_univ, on='Univ') \
    [['Restaurant Name', 'INSTNM', 'Distance']]


结果:

                    Restaurant Name                                       INSTNM   Distance
Store Univ
0     1               Weymouth Dual  New England College of Business and Finance  15.651923
1     4               Somerset Dual                            Bay State College  68.921108
2     3     Westboro Mass Pike West           Bancroft School of Massage Therapy   9.580468
3     2     Charlton Mass Pike East                           Assumption College  26.514269
4     2     Charlton Mass Pike West                           Assumption College  26.508821

07-25 23:58