# SciPy for computeing Distance between points

SciPy defines some useful functions for computing distances between sets of points.

1、The function scipy.spatial.distance.pdist computes the distance between all pairs of points in a given set:

import numpy as np
from scipy.spatial.distance import pdist, squareform

# Create the following array where each row is a point in 2D space:
# [[0 1]
#  [1 0]
#  [2 0]]
x = np.array([[0, 1], [1, 0], [2, 0]])
print(x)

# Compute the Euclidean distance between all rows of x.
# d[i, j] is the Euclidean distance between x[i, :] and x[j, :],
# and d is the following array:
# [[ 0.          1.41421356  2.23606798]
#  [ 1.41421356  0.          1.        ]
#  [ 2.23606798  1.          0.        ]]
d = squareform(pdist(x, 'euclidean'))
print(d)

array=

[dx1(row1),x1(row1),dx1(row1),x1(row2),dx1(row1),x1(row3)]

[dx1(row2),x1(row1),dx1(row2),x1(row2),dx1(row2),x1(row3)]

[dx1(row3),x1(row1),dx1(row3),x1(row2),dx1(row3),x1(row3)]

2、

1. In [1]: from scipy.spatial.distance import cdist

2. ...: import numpy as np

3. ...: x1 =np.array([(1,3),(2,4),(5,6)])

4. ...: x2 =[(3,7),(4,8),(6,9)]

5. ...: cdist(x1,x2,metric='euclidean')

6. ...:

7. Out[1]:

8. array([[ 4.47213595, 5.83095189, 7.81024968],

9. [ 3.16227766, 4.47213595, 6.40312424],

10. [ 2.23606798, 2.23606798, 3.16227766]])

array=

[dx1(row1),x2(row1),dx1(row1),x2(row2),dx3(row1),x3(row3)]

[dx1(row2),x2(row1),dx1(row2),x2(row2),dx3(row2),x3(row3)]

[dx1(row3),x2(row1),dx1(row3),x2(row2),dx3(row3),x3(row3)]

1. In [2]: np.power((1-3)**2 +(3-7)**2,1/2)

2. Out[2]: 4.4721359549995796

--------------------- 本文来自 每天进步一点点2017 的CSDN 博客 ，全文地址请点击：https://blog.csdn.net/kancy110/article/details/75675574?utm_source=copy

12-26 109
11-26 257
03-28 106
11-23 2179