在 pandas 数据框中找到从点到行的欧几里得距离 [英] Find euclidean distance from a point to rows in pandas dataframe

查看:84
本文介绍了在 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

我想从列表L1中保存的特定位置找到这些坐标的欧式距离

I want to find the euclidean distance of these coordinates from a particulat location saved in a list L1

L1 = [11.344,7.234]

我想在df中创建我有距离的新列

i want to create a new column in df where i have the distances

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

我知道使用math.hypot()查找两点之间的欧几里得距离:

i know to find euclidean distance between two points using math.hypot():

dist = math.hypot(x2 - x1, y2 - y1)

如何使用Apply或遍历行来给我距离来编写函数.

How do i write a function using apply or iterate over rows to give me distances.

推荐答案

使用矢量化方法

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

也可以是

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


选项2 使用Numpy内置的np.linalg.norm向量范数.


Option 2 Use Numpy's built-in np.linalg.norm vector 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)

这篇关于在 pandas 数据框中找到从点到行的欧几里得距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆