Python에서 유클리드 거리를 계산하는 방법(예제 포함)
두 벡터 A와 B 사이의 유클리드 거리는 다음과 같이 계산됩니다.
유클리드 거리 = √ Σ(A i -B i ) 2
Python에서 두 벡터 사이의 유클리드 거리를 계산하려면 numpy.linalg.norm 함수를 사용할 수 있습니다.
#import functions import numpy as np from numpy. linalg import norm #define two vectors a = np.array([2, 6, 7, 7, 5, 13, 14, 17, 11, 8]) b = np.array([3, 5, 5, 3, 7, 12, 13, 19, 22, 7]) #calculate Euclidean distance between the two vectors norm(ab) 12.409673645990857
두 벡터 사이의 유클리드 거리는 12.40967 입니다.
두 벡터의 길이가 같지 않으면 이 함수는 경고 메시지를 생성합니다.
#import functions import numpy as np from numpy. linalg import norm #define two vectors a = np.array([2, 6, 7, 7, 5, 13, 14]) b = np.array([3, 5, 5, 3, 7, 12, 13, 19, 22, 7]) #calculate Euclidean distance between the two vectors norm(ab) ValueError : operands could not be broadcast together with shapes (7,) (10,)
이 함수를 사용하여 Pandas DataFrame의 두 열 사이의 유클리드 거리를 계산할 수도 있습니다.
#import functions import pandas as pd import numpy as np from numpy. linalg import norm #define DataFrame with three columns df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29], 'assists': [5, 7, 7, 9, 12, 9, 9, 4], 'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]}) #calculate Euclidean distance between 'points' and 'assists' norm(df[' points '] - df[' assists ']) 40.496913462633174
두 열 사이의 유클리드 거리는 40.49691 입니다.
코멘트
1. Python에서 유클리드 거리를 계산하는 방법은 여러 가지가 있지만 이 Stack Overflow 스레드에서 설명하는 것처럼 여기에 설명된 방법이 가장 빠른 것으로 나타났습니다.
2. 여기에서 numpy.linalg.norm 함수에 대한 전체 문서를 찾을 수 있습니다.
3. 유클리드 거리에 대해 자세히 알아보려면 이 Wikipedia 페이지를 참조 하세요 .