Home »
Python »
Python Programs
How to calculate the minimum Euclidean distance between points in two different NumPy arrays?
Learn, how to calculate the minimum Euclidean distance between points in two different NumPy arrays?
By Pranit Sharma Last updated : December 24, 2023
NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.
Problem statement
Suppose that we are given two numpy arrays containing x and y coordinates as their elements. We need to find the minimum Euclidean distance between each point in one array with all the points in the other array where the arrays are not necessarily the same size.
Calculating the minimum Euclidean distance between points in two different NumPy arrays
For this purpose, an optimal and time-saving solution can be achieved using scipy.spatial.KDTree. It creates a kd-tree for quick nearest-neighbor lookup. This class provides an index into a set of k-dimensional points which can be used to rapidly look up the nearest neighbors of any point.
Let us understand with the help of an example,
Python code to calculate the minimum Euclidean distance between points in two different NumPy arrays
# Importing spatial
from scipy import spatial
# Import numpy
import numpy as np
# Creating two arrays
arr1 = np.array([[243, 3173],[525, 2997]])
arr2 = np.array([[682, 2644],[277, 2651],[396, 2640]])
# Display orignal arrays
print("Original Array1:\n",arr1,"\n")
print("Original Array2:\n",arr2,"\n")
# Calculating minimum distance of each point
# of a array from set of points of other array
kd = spatial.KDTree(arr2)
dist, min = kd.query(arr1)
# Display result
print("Result:\n",dist)
Output
Python NumPy Programs »