2014-11-09 2 views
3

서로의 최대 거리 내에서 (x, y) 점 쌍을 찾으려고합니다. 가장 간단한 방법은 DataFrame을 생성하고 주어진 점 (x_0, y_0)의 거리 r 내에 좌표 (x, y)가있는 점이 있는지 계산하여 점 하나 하나씩 살펴 보는 것입니다. 그리고, 항상 올바른 쌍 (I가 표시되지 않습니다 명시된 거리에 있습니다 포인트 참조) 찾지 못하는 것, 모든 2.팬더 : 최대 거리 내에서 포인트 찾기

%pylab inline 
import pandas as pd 

def find_nbrs(low, high, num, max_d): 
    x = random.uniform(low, high, num) 
    y = random.uniform(low, high, num) 
    points = pd.DataFrame({'x':x, 'y':y}) 

    tot_nbrs = 0 

    for i in arange(len(points)): 
     x_0 = points.x[i] 
     y_0 = points.y[i] 

     pt_nbrz = points[((x_0 - points.x)**2 + (y_0 - points.y)**2) < max_d**2] 
     tot_nbrs += len(pt_nbrz) 
     plot (pt_nbrz.x, pt_nbrz.y, 'r-') 

    plot (points.x, points.y, 'b.') 
    return tot_nbrs 

print find_nbrs(0, 1, 50, 0.1) 
  1. 먼저 발견 쌍의 총 수를 나눕니다.

  2. plot(..., 'or')으로 작성하면 모든 점을 강조 표시합니다. 즉, pt_nbrz = points[((x_0 - points.x)**2 + (y_0 - points.y)**2) < max_d**2]은 적어도 하나 (x, y)를 반환합니다. 왜? 비교가 거짓이면 빈 배열을 반환하지 않아야합니까?

  3. 위의 모든 것을 팬더에서 어떻게 우아하게 처리 할 수 ​​있습니까? 예를 들어, 각 요소를 반복하지 않아도됩니다.

+0

저를 수정하지만 당신이 O를하고있는 (n)의 검색 당신을 생각 할 때 O (n^2) 검색이 필요합니다. x0 : y0, x1 : y1, x2 : y2 ... 기본적으로 x0 : y0, x0 : y1, ... x1 : y0, x1 : y1, x1 : y2 .... – Greg

+0

하지만 내가 뭘 원하는지에 대해 틀렸다면이게 잘 될거야. http://stackoverflow.com/questions/1401712/how-can-the-euclidean-distance-be-calculated - 함께 numpy – Greg

+0

링크 주셔서 감사합니다. 대답에도 불구하고 numpy.linalg.norm을 사용하여 거리를 계산하는 방법을 알아 내는데 어려움이 있습니다. 예제에서 a와 b는 어떤 형식이어야합니까? Re : O (n^2), 나는 그것이 무엇을하고 있었는지, 즉 각 데이터 프레임 요소를 살펴보고 비교를 만족시키는 다른 모든 요소를 ​​찾는 것이라고 생각했습니다. 두 쌍의 모든 쌍둥이를 식별해야하므로 번호를 얻으려면 finall 집계를 2로 나누면됩니다. –

답변

7

찾고있는 기능은 scipy's spatial distance module에 포함되어 있습니다.

다음은 사용 방법의 예입니다. 진짜 마법은 squareform(pdist(points))입니다. 시각화 목적

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

points = np.random.uniform(-.5, .5, (1000,2)) 

# Compute the distance between each different pair of points in X with pdist. 
# Then, just for ease of working, convert to a typical symmetric distance matrix 
# with squareform. 
dists = squareform(pdist(points)) 

poi = points[4] # point of interest 
dist_min = .1 
close_points = dists[4] < dist_min 

print("There are {} other points within a distance of {} from the point " 
    "({:.3f}, {:.3f})".format(close_points.sum() - 1, dist_min, *poi)) 

There are 27 other points within a distance of 0.1 from the point (0.194, 0.160)

: 내가 틀렸다면

f,ax = plt.subplots(subplot_kw= 
    dict(aspect='equal', xlim=(-.5, .5), ylim=(-.5, .5))) 
ax.plot(points[:,0], points[:,1], 'b+ ') 
ax.plot(poi[0], poi[1], ms=15, marker='s', mfc='none', mec='g') 
ax.plot(points[close_points,0], points[close_points,1], 
    marker='o', mfc='none', mec='r', ls='') # draw all points within distance 

t = np.linspace(0, 2*np.pi, 512) 
circle = dist_min*np.vstack([np.cos(t), np.sin(t)]).T 
ax.plot((circle+poi)[:,0], (circle+poi)[:,1], 'k:') # Add a visual check for that distance 
plt.show() 

enter image description here