Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

python - Find euclidean distance from a point to rows in pandas dataframe

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

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

L1 = [11.344,7.234]

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

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use vectorized approach

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

Which can also be

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

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...