Shu*_*m R 6 python euclidean-distance dataframe pandas
我有一个数据帧
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
Run Code Online (Sandbox Code Playgroud)
我想从保存在列表L1中的特定位置找到这些坐标的欧氏距离
L1 = [11.344,7.234]
Run Code Online (Sandbox Code Playgroud)
我想在df中创建一个新列,我有距离
id lat long distance
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
Run Code Online (Sandbox Code Playgroud)
我知道使用math.hypot()找到两点之间的欧氏距离:
dist = math.hypot(x2 - x1, y2 - y1)
Run Code Online (Sandbox Code Playgroud)
如何使用应用或迭代行来编写函数来给出距离.
使用矢量化方法
In [5463]: (df[['lat', 'long']] - np.array(L1)).pow(2).sum(1).pow(0.5)
Out[5463]:
0 8.369161
1 18.523838
2 26.066777
3 18.632320
4 22.546096
dtype: float64
Run Code Online (Sandbox Code Playgroud)
哪个也可以
In [5468]: df['distance'] = df[['lat', 'long']].sub(np.array(L1)).pow(2).sum(1).pow(0.5)
In [5469]: df
Out[5469]:
id lat long distance
0 1 12.654 15.50 8.369161
1 2 14.364 25.51 18.523838
2 3 17.636 32.53 26.066777
3 5 12.334 25.84 18.632320
4 9 32.224 15.74 22.546096
Run Code Online (Sandbox Code Playgroud)
选项2使用Numpy的内置np.linalg.norm
向量规范.
In [5473]: np.linalg.norm(df[['lat', 'long']].sub(np.array(L1)), axis=1)
Out[5473]: array([ 8.36916101, 18.52383805, 26.06677732, 18.63231966, 22.5460958 ])
In [5485]: df['distance'] = np.linalg.norm(df[['lat', 'long']].sub(np.array(L1)), axis=1)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8962 次 |
最近记录: |