How to calculate the distance between two points, for many consequent points, within groups in python

Related searches

I have the following df

       id             xx            yy  time
0       1  553343.041098  4.178420e+06     1
1       1  553343.069815  4.178415e+06     2
2       1  553343.069815  4.178415e+06     3
3       2  553343.950755  4.178415e+06     1
4       2  553341.343829  4.178410e+06     6

The xx and yy is the position of each id at a certain point in time.

I would like to create an extra column in this df, which will be the difference in distance from one point of time to another (going from the smallest value of time to the next bigger, to the next bigger one etc), within the id group.

Is there a Pythonic way of doing so ?


You can do like below.

I didn't do df['distance_meters'] because it is straight forward.

df['xx_diff']=df.groupby('id')['xx'].diff()**2
df['yy_diff']=df.groupby('id')['yy'].diff()**2

If you don't need ['xx_diff'] & ['yy_diff'] columns in your dataframe, you can directly use the code below.

df['distance']= np.sqrt(df.groupby('id')['xx'].diff()**2+df.groupby('id')['yy'].diff()**2)

Output

    id            xx         yy time    xx_diff3    yy_diff3    distance
0   1   553343.041098   4178420.0   1   NaN            NaN      NaN
1   1   553343.069815   4178415.0   2   0.000825       25.0     5.000082
2   1   553343.069815   4178415.0   3   0.000000       0.0      0.000000
3   2   553343.950755   4178415.0   1   NaN            NaN      NaN
4   2   553341.343829   4178410.0   6   6.796063      25.0      5.638800

Python: Compute the distance between two points, Python Exercises, Practice and Solution: Write a Python program to compute the distance between the points (x1, y1) and (x2, y2). Calculate Distance Between GPS Points in Python 09 Mar 2018. When working with GPS, it is sometimes helpful to calculate distances between points. But simple Euclidean distance doesn’t cut it since we have to deal with a sphere, or an oblate spheroid to be exact. So we have to take a look at geodesic distances.


I dont know if there is a more efficient way to do this, but here is a solution:

import numpy as np
df['xx_diff'] = df.groupby('id')['xx'].rolling(window=2).apply(lambda x: (x[1] - x[0])**2).reset_index(drop=True)
df['yy_diff'] = df.groupby('id')['yy'].rolling(window=2).apply(lambda x: (x[1] - x[0])**2).reset_index(drop=True)
df['distance_meters'] = np.sqrt(df['xx_diff'] + df['yy_diff'])

A more pythonic answer will be accepted :)

Pandas Data Series: Compute the Euclidean distance between two , Python Pandas: Compute the Euclidean distance between two given is the " ordinary" straight-line distance between two points in Euclidean� Match set of x,y points to another set that is scaled, rotated, translated, and with missing elements 2 Check whether a point exists in circle sector or not with Python


Try This:

import pandas as pd
import math

def calc_distance(values):
    values.sort_values('id', inplace = True)
    values['distance_diff'] = 0
    values.reset_index(drop=True, inplace=True)
    for i in range(values.shape[0]-1):
        p1 = list(values.loc[i, ['xx', 'yy']])
        p2 = list(values.loc[i+1, ['xx', 'yy']])
        values.loc[i,'distance_diff'] = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2))
    return values

lt = []
lt.append(df.groupby(['id']).apply(calc_distance))
print(pd.concat(lt, ignore_index=True))

Output:

   id             xx         yy  time  distance_diff
0   1  553343.041098  4178420.0     1       5.000082
1   1  553343.069815  4178415.0     2       0.000000
2   1  553343.069815  4178415.0     3       0.000000
3   2  553343.950755  4178415.0     1       5.638800
4   2  553341.343829  4178410.0     6       0.000000

Making a pairwise distance matrix with pandas — Drawing from Data, This is a somewhat specialized problem that forms part of a lot of data science and measure, for each different country, the number of medals they've won in each different sport: many of which are implemented in the scipy.spatial. distance module. Think of it as the straight line distance between the two points in space� Write a python program that declares a function named distance. The purpose of the function is to calculate the distance between two points and return the result. The function should define 4 parameter variables.


How to calculate Distance in Python and Pandas using Scipy spatial , The real works starts when you have to find distances between two coordinates or the elements are more often referred to as points, nodes or vertices to radians because most of the scipy distance metrics functions takes� Correct Answer. To calculate distance between two points, you could just do. import mathdef calculateDistance(x1,y1,x2,y2): dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) return distprint calculateDistance(x1, y1, x2, y2) if it is along a line, you could just split the line with the points and use the length of the line for that.


Distance in Spatial Analysis: Measurement, Bias, and Alternatives , While measuring the distance between two points is straightforward, many inside a polygon, in many applications, detailed information about an individual's location such as census tracts, block groups, and blocks, are rectangles or close to The distance calculation is performed in Python 3.7, and the� To find the distance between two points ( x 1, y 1) and ( x 2, y 2 ), all that you need to do is use the coordinates of these ordered pairs and apply the formula pictured below. The distance formula is. Distance = ( x 2 − x 1) 2 + ( y 2 − y 1) 2.


Take the coordinates of two points you want to find the distance between. Think of the distance between any two points as a line. The length of this line can be found by using the distance formula: \sqrt((x_2 - x_1)^2 + (y_2 - y_1)^2).