w3resource

Calculating Pairwise Euclidean distances in a 3x3 array using NumPy

NumPy: Advanced Exercise-33 with Solution

Write a NumPy program to create a 3x3 array with random values and calculate the pairwise Euclidean distance between each pair of rows.

Sample Solution:

Python Code:

import numpy as np
from scipy.spatial import distance

# Create a 3x3 array with random values
array = np.random.random((3, 3))

# Print the original array
print("Original Array:\n", array)

# Calculate pairwise Euclidean distances between each pair of rows
pairwise_distances = distance.cdist(array, array, 'euclidean')

# Print the pairwise distances
print("Pairwise Euclidean distances between each pair of rows:\n", pairwise_distances)

Output:

Original Array:
 [[0.47864642 0.98844776 0.46615728]
 [0.69647683 0.8741336  0.80914819]
 [0.17481078 0.88159549 0.2119323 ]]
Pairwise Euclidean distances between each pair of rows:
 [[0.         0.42209072 0.41032164]
 [0.42209072 0.         0.79300566]
 [0.41032164 0.79300566 0.        ]]

Explanation:

  • Import NumPy and SciPy: Import the NumPy library for array operations and the distance module from SciPy for distance calculations.
  • Create a Random 3x3 Array: Generate a 3x3 array filled with random values using np.random.random.
  • Print the Original Array: Print the original 3x3 array for reference.
  • Calculate Pairwise Euclidean Distances: Use distance.cdist with the metric 'euclidean' to compute the pairwise Euclidean distances between each pair of rows.
  • Print the Pairwise Distances: Print the resulting pairwise Euclidean distances.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Shifting all elements in a 4x4 array downwards using NumPy.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.