代码之家  ›  专栏  ›  技术社区  ›  Demetri Pananos

函数认为我正在通过一个浮点

  •  2
  • Demetri Pananos  · 技术社区  · 8 年前

    我想计算两个数组中所有坐标对之间的距离。以下是我写的一些代码:

    def haversine(x,y):
        """
        Calculate the great circle distance between two points 
        on the earth (specified in decimal degrees)
        """
        # convert decimal degrees to radians 
        print(type(x))
        lat1, lon1 = np.radians(x)
        lat2, lon2 = np.radians(y)
    
        # haversine formula 
        dlon = lon2 - lon1 
        dlat = lat2 - lat1 
        a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2)**2
        c = 2 * np.arcsin(np.sqrt(a)) 
        r = 6371 # Radius of earth in kilometers. Use 3956 for miles
        return c * r
    
    haversine = np.vectorize(haversine)
    

    阵列是 gas_coords 和 postal_coords .注意

    type(postal_coords)
    >>>numpy.ndarray
    
    type(gas_coords)
    >>>numpy.ndarray
    

    每个数组都有两列。

    当我试图计算距离时 using scipy.spatial.distance.cdist 我得到以下错误:

    in haversine(x, y)
          6     # convert decimal degrees to radians
          7     print(type(x))
    ---->; 8     lat1,lon1 =np.radians(x)
          9     lat2,lon2 = np.radians(y)
         10 
    
    TypeError: 'numpy.float64' object is not iterable
    

    haversine 似乎认为输入 x 是浮点而不是数组。即使当我将数组传递到 哈弗斯林 喜欢 haversine(np.zeros(2),np.zeros(2)) 同样的问题也出现了。我应该注意到,这只发生在矢量化通过 np.vectorize .

    从看 哈弗斯林 ,参数不会以任何方式更改。导致错误的原因是什么?

    下面是一个最小的工作示例:

    import numpy as np
    from scipy.spatial.distance import cdist
    
    gas_coords = np.array([[50, 80], [50, 81]])
    postal_coords = np.array([[51, 80], [51, 81]])
    
    
    cdist(postal_coords, gas_coords, metric = haversine)
    
    
    >>>array([[ 111.19492664,  131.7804742 ],
              [ 131.7804742 ,  111.19492664]])
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   JE_Muc    8 年前

    给定所需的输出,可以通过不向量化 haversine 函数,因为它将scalars传递给函数(如上面的注释中所述)。所以你可以打电话 cdist 使用:

    import numpy as np
    from scipy.spatial.distance import cdist
    
    def haversine(x, y):
        """
        Calculate the great circle distance between two points 
        on the earth (specified in decimal degrees)
        """
        # convert decimal degrees to radians 
        print(type(x))
        lat1, lon1 = np.radians(x)
        lat2, lon2 = np.radians(y)
    
        # haversine formula 
        dlon = lon2 - lon1 
        dlat = lat2 - lat1 
        a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2)**2
        c = 2 * np.arcsin(np.sqrt(a)) 
        r = 6371 # Radius of earth in kilometers. Use 3956 for miles
        return c * r
    
    gas_coords = np.array([[50, 80], [50, 81]])
    postal_coords = np.array([[51, 80], [51, 81]])
    
    cdist(postal_coords, gas_coords, metric=haversine)