在python中计算熊猫DataFrame连续点的Harvesine和初始方位

问题描述

提供这种计算的包太多了,尽管其中大多数是基于点而不是数据框,或者我可能犯了一个错误! 我发现这种方法可以使用我的纬度和经度列的熊猫数据框:

def haversine(lat1,lon1,lat2,lon2,to_radians=True,earth_radius=6378137):
   """
   slightly modified version: of http://stackoverflow.com/a/29546836/2901002

   Calculate the great circle distance between two points
   on the earth (specified in decimal degrees or in radians)

   All (lat,lon) coordinates must have numeric dtypes and be of equal length.
   """
   if to_radians:
       lat1,lon2 = map(np.radians,[lat1,lon2])
       a = np.sin((lat2-lat1)/2.0)**2 + \
           np.cos(lat1) * np.cos(lat2) * np.sin((lon2-lon1)/2.0)**2
   return earth_radius * 2 * np.arcsin(np.sqrt(a))

但是我尝试过的所有初始方位角或方位角,不接受数据帧系列,尝试使用 numpy 数组仍然会返回零! 对于数据帧的连续行,是否有某种方法可以这样做?我想计算连续点之间的初始方位。在 R 中,轴承函数将使用数据框完成这项工作,只是想知道 Python 中是否有等价物。

解决方法

更新: 我发现了问题。我使用 R 方法能够找到连续行之间的方位,所以我基本上删除了第一行和最后一行,制作了两组具有两列的数据框,但它与 shift() 完美配合,我编写了自己的方位函数这比使用那里的更容易...... 所以我从 pts 我的主数据帧制作了下面的两个数据帧: latlon_a = pts latlon_b = pts.shift() 以及我自己的初始承载函数:

def initial_bearing(lon1,lat1,lon2,lat2):
   """
   My own version based on R source

   Calculate the initial bearing between two points

   All (latitude,longitude) coordinates must have numeric dtypes and be of equal length.
   """
   lat1,lon1,lat2,lon2 = map(np.radians,[lon1,lat2])
   delta1 = lon1-lon2
   term1 = np.sin(delta1) * np.cos(lat2)
   term2 = np.cos(lat1) * np.sin(lat2)
   term3 = np.sin(lat1) * np.cos(lat2) * np.cos(delta1)
   rad = np.arctan2(term1,(term2-term3))
   bearing = np.rad2deg(rad)
   return (bearing + 360) % 360


bearing = initial_bearing(latlon_a['longitude'],latlon_a['latitude'],latlon_b['longitude'],latlon_b['latitude'])

这对我来说非常有效,并且恢复了最初的方向。对于轴承,您只需替换或添加以下行即可返回: 回报(轴承 + 180)% 360