Free cookie consent management tool by TermsFeed Convert a condensed distance matrix into a square matrix using SciPy | Pythontic.com

Convert a condensed distance matrix into a square matrix using SciPy

Overview:

  • If the pairwise distances between a set of points is available the distances can be obtained as a square matrix using the SciPy function squareform().

  • Given a set of points to get only the upper or lower triangular portion the pdist() function can be used.

Example:

The bird dataset used in the hierarchical clustering example is used here.

# Example Python program that forms the pairwise 
# distances between points as a square matrix
# using the SciPy function squareform()

import scipy.spatial.distance as dist
import numpy

# The data points
brain_weights_birds  = numpy.array([[0.5,    0.01365], [0.45,   0.00725],
                                    [0.3,    0.001], [1.8,    0.012],
                                    [2,      0.022], [1,      0.065]
                                   ])

# Get the condensed distance matrix
inTriangularForm    = dist.pdist(brain_weights_birds)

# Form the square matrix of pairwise distances
inSquareForm         = dist.squareform(inTriangularForm)

print("Pairwise distances:")
print(inTriangularForm)
print("Pairwise distances as a square matrix:")
print(inSquareForm)

 

 

Output:

Pairwise distances:
[0.05040794 0.20039966 1.30000105 1.50002324 0.50262991 0.15013015
 1.35000836 1.55007018 0.55302356 1.50004033 1.7001297  0.70291963
 0.20024984 0.8017537  1.00092407]
Pairwise distances as square form:
[[0.         0.05040794 0.20039966 1.30000105 1.50002324 0.50262991]
 [0.05040794 0.         0.15013015 1.35000836 1.55007018 0.55302356]
 [0.20039966 0.15013015 0.         1.50004033 1.7001297  0.70291963]
 [1.30000105 1.35000836 1.50004033 0.         0.20024984 0.8017537 ]
 [1.50002324 1.55007018 1.7001297  0.20024984 0.         1.00092407]
 [0.50262991 0.55302356 0.70291963 0.8017537  1.00092407 0.        ]]

 


Copyright 2025 © pythontic.com