 Open in App
Not now

# Python – Distance between collections of inputs

• Last Updated : 24 Feb, 2023

scipy.stats.cdist(array, axis=0) function calculates the distance between each pair of the two collections of inputs.

Parameters : array: Input array or object having the elements to calculate the distance between each pair of the two collections of inputs.
axis: Axis along which to be computed. By default axis = 0
Returns : distance between each pair of the two collections of inputs.

Code #1 : 2D Array

## Python3

 `from` `scipy.spatial.distance ``import` `cdist``a ``=` `[[``1``, ``3``, ``27``], [``3``, ``6``, ``8``]]``arr1 ``=` `cdist(a, a)` `print``("Value of cdist ``is` `:", arr1)`

Output:

```Value of cdist is : [[ 0.         19.33907961]
[19.33907961  0.        ]]```

Time complexity: O(n^2), where n is the number of elements in the input list ‘a’.
Auxiliary space: O(n^2).

Code #2 : 3D Array

## Python3

 `from` `scipy.spatial.distance ``import` `cdist`` ` `arr1 ``=` `[[``1``, ``3``, ``27``], ``        ``[``3``, ``4``, ``6``], ``        ``[``7``, ``6``, ``3``], ``        ``[``3``, ``6``, ``8``]] ``   ` `print``("Value of cdist ``is` `:", cdist(arr1, arr1)) `

Output:

```Value of cdist is : [[ 0.         21.11871208 24.91987159 19.33907961]
[21.11871208  0.          5.38516481  2.82842712]
[24.91987159  5.38516481  0.          6.40312424]
[19.33907961  2.82842712  6.40312424  0.        ]]```

Time complexity: O(n^2), where n is the number of points in arr1.
Auxiliary space: O(n^2),

My Personal Notes arrow_drop_up