Pandas - Euclidean Distance Between Columns

Viewed 2349

I have a dataframe as follows:

           uuid        x_1         y_1         x_2         y_2
0        di-ab5      82.31      184.20      148.06      142.54  
1        di-de6      92.35      185.21       24.12       16.45
2        di-gh7     123.45        0.01         NaN         NaN 
...

I am trying to calculate the euclidean distance between [x_1, y_1] and [x_2, y_2] in a new column (not real values in this example).

           uuid       dist
0        di-ab5      12.31    
1        di-de6      62.35   
2        di-gh7        NaN

Caveats:

  1. some rows have NaN on some of the datapoints
  2. it is okay to represent data in the original dataframe as points (i.e. [1.23, 4.56]) instead of splitting up the x and y coordinates

I am currently using the following script:

df['dist']  = np.sqrt((df['x_1'] - df['x_2'])**2 + (df['y_1'] - df['y_2'])**2)

But it seems verbose and often fails. Is there a better way to do this using pandas, numpy, or scipy?

4 Answers

You can use np.linalg.norm, i.e.:

df['dist'] = np.linalg.norm(df.iloc[:, [1,2]].values - df.iloc[:, [3,4]], axis=1)

Output:

     uuid     x_1     y_1     x_2     y_2        dist
0  di-ab5   82.31  184.20  148.06  142.54   77.837125
1  di-de6   92.35  185.21   24.12   16.45  182.030960
2  di-gh7  123.45    0.01     NaN     NaN         NaN
def getDist( df, a, b ):
    return np.sqrt((df[f'x_{a}']-df[f'x_{b}'])**2+(df[f'y_{a}']-df[f'y_{b}'])**2)
np.sqrt((df.filter(like='x').agg('diff',1).sum(1)**2)+(df.filter(like='y').agg('diff',1).sum(1)**2))

How it works

Filter x and y respectively

df.filter(like='x')

Find the cross column difference and square it.

df.filter(like='x').agg('diff',1).sum(1)**2

Add the two outcomes together and find the square root.

np.sqrt((df.filter(like='x').agg('diff',1).sum(1)**2)+(df.filter(like='y').agg('diff',1).sum(1)**2))

Another solution using numpy:

diff = (df[['x_1','y_1']].to_numpy()-df[['x_2','y_2']].to_numpy())
df['dist'] = np.sqrt((diff*diff).sum(-1))

output:

    uuid    x_1     y_1     x_2     y_2     dist
0   di-ab5  82.31   184.20  148.06  142.54  77.837125
1   di-de6  92.35   185.21  24.12   16.45   182.030960
2   di-gh7  123.45  0.01    NaN     NaN     NaN
Related