Find euclidean distance from a point to rows in pandas dataframe

前端 未结 2 1729
南笙
南笙 2020-12-19 07:32

i have a dataframe

id    lat      long
1     12.654   15.50
2     14.364   25.51
3     17.636   32.53
5     12.334   25.84
9     32.224   15.74
2条回答
  •  悲&欢浪女
    2020-12-19 08:00

    Translating [(x2 - x1)2 + (y2 - y1)2]1/2 into pandas vectorised operations, you have:

    df['distance'] = (df.lat.sub(11.344).pow(2).add(df.long.sub(7.234).pow(2))).pow(.5)         
    df
    
           lat   long   distance
    id                          
    1   12.654  15.50   8.369161
    2   14.364  25.51  18.523838
    3   17.636  32.53  26.066777
    5   12.334  25.84  18.632320
    9   32.224  15.74  22.546096
    

    Alternatively, using arithmetic operators:

    (((df.lat - 11.344) ** 2) + (df.long - 7.234) ** 2) ** .5
    

提交回复
热议问题