假设您有一个
dist要最小化的距离函数:
def dist(lat1, long1, lat2, long2): return np.abs((lat1-lat2)+(long1-long2))
对于给定的位置,您可以找到最近的车站,如下所示:
lat = 39.463744long = -76.119411weather.apply( lambda row: dist(lat, long, row['Latitude'], row['Longitude']), axis=1)
这将计算到所有气象站的距离。使用
idxmin您可以找到最近的电台名称:
distances = weather.apply( lambda row: dist(lat, long, row['Latitude'], row['Longitude']), axis=1)weather.loc[distances.idxmin(), 'StationName']
让我们将所有这些放到一个函数中:
def find_station(lat, long): distances = weather.apply( lambda row: dist(lat, long, row['Latitude'], row['Longitude']), axis=1) return weather.loc[distances.idxmin(), 'StationName']
现在,您可以通过将其应用于
locations数据框来获取所有最近的测站:
locations.apply( lambda row: find_station(row['Latitude'], row['Longitude']), axis=1)
输出:
0 WALTHAM1 WALTHAM2 PORTST.LUCIE3 WALTHAM4 PORTST.LUCIE



