# 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?
Submitted by Pranit Sharma, on February 26, 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.

## Calculating the minimum Euclidean distance between points in two different NumPy arrays

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.

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:

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates