我有一个带有端口位置和端口ID(lon,lat,port_id)的数据框。我也有另一个带有船舶导航观测数据的数据框(ship_id,lon,lat,timestamp)PS。相同的ship_id可以有多个观察结果
如果船舶的位置在港口半径2公里之内,我想在船舶导航表中添加一列,其中包含port_id的值。
我已经具有测量两个地理位置之间的距离的功能,但是迭代舰船位置的语法是什么呢?将它们与港口位置进行比较并分别填充列
这是两个地理位置之间的距离测量功能的代码:
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lat1 = radians(lat1)
lon1 = radians(lon1)
lat2 = radians(lat2)
lon2 = radians(lon2)
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
distance_btwn_points= c * r
return distance_btwn_points
在此处将port_id列添加到船舶导航数据框
radius = 2.00 # in kilometer
ship_navigation_port=ship_navigation.copy()
ship_navigation_port['port_id']= 0
for port in ports_location['port_id']:
for index, row in ship_navigation_port.iterrows():
ship_navigation_port['port_id']= np.where(haversine( ports_location['lon'][port], ports_location['lat'][port], row['lon'], row['lat'])<= radius, ports_location['port_id'][port], 0)
能否请您以正确的语法帮助我