I'm trying to measure the shortest euclidean distance of each point to the nearest group of points. Using below, I have 6 unique points displayed in x,y
at two separate time points. I have a separate xy point recorded in x_ref, y_ref
, which I pass a radius around. So for each point outside this radius, I want to find the shortest distance to any point within the radius. For points within the radius, just return 0.
calculate_distances
measures the distance between each specific point and the remaining points. I'm hoping to return the distance to the nearest point within the radius.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import pdist, squareform
df = pd.DataFrame({
'Time' : [1,1,1,1,1,1,2,2,2,2,2,2],
'Item' : ['A','B','C','D','E','F','A','B','C','D','E','F'],
'x' : [5,5,8,3,6,2,6,7,4,2,7,6],
'y' : [-2,0,-2,0,0,4,-1,2,-3,4,-4,2],
'x_ref' : [4,4,4,4,4,4,4,4,4,4,4,4],
'y_ref' : [-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2],
})
# Determine square distance
square_dist = (df['x_ref'] - df['x']) ** 2 + (df['y_ref'] - df['y']) ** 2
# Return df of items within radius
inside_radius = df[square_dist <= 3 ** 2].copy()
def calculate_distances(df):
id_distances = pd.DataFrame(
squareform(pdist(df[['x','y']].to_numpy())),
columns = df['Item'],
index = df['Item'],
)
return id_distances
df_distances = df.groupby(['Time']).apply(calculate_distances).reset_index()
Intended output:
Time Item x y x_ref y_ref distance
0 1 A 5 -2 3 -2 0.000000 # within radius 0
1 1 B 5 0 3 -2 0.000000 # within radius 0
2 1 C 8 -2 3 -2 2.828427 # nearest within radius is E
3 1 D 3 0 3 -2 0.000000 # within radius 0
4 1 E 6 0 3 -2 0.000000 # within radius 0
5 1 F 2 4 3 -2 4.123106 # nearest within radius is D
6 2 A 6 -1 4 -2 0.000000 # within radius 0
7 2 B 7 2 4 -2 3.162278 # nearest within radius is A
8 2 C 4 -3 4 -2 0.000000 # within radius 0
9 2 D 2 4 4 -2 6.403124 # nearest within radius is A
10 2 E 7 -4 4 -2 3.162278 # nearest within radius is C or A
11 2 F 6 2 4 -2 3.000000 # nearest within radius is A
inside_radius
– jonboy