在Python中在一定距离内重复删除

时间:2015-03-28 19:41:37

标签: python performance numpy distance python-2.x

我有两个numpy.arrays的点(形状(m,2)和(n,2)),如下所示:

A = numpy.array([[1,2],[3,4]])
B = numpy.array([[5,6],[7,8],[9,2]])

我需要将它们合并到具有下一个条件的数组中:

  

如果距离小于或等于epsilon有两个点,只需留下一个

我有这段代码,但速度很慢:

import numpy as np

eps = 0.1
A = np.array([[1,2],[3,4]])
B = np.array([[5,6],[7,8],[9,2]])

for point in B:
    if not (np.amin(np.linalg.norm(A-point)) <= eps):
        A = np.append(  A ,  [point], axis=0)

使用numpy的最佳方法是什么?

非常感谢!

1 个答案:

答案 0 :(得分:1)

您可以先计算Delaunay triangulation,从中可以轻松提取相邻点列表:

import numpy as np
from itertools import product
from scipy.spatial import Delaunay

eps = 3.  # choose value, which filters out some points
A = np.array([[1,2],[3,4]])
B = np.array([[5,6],[7,8],[9,2]])

# triangulate points:
pts = np.vstack([A, B])
tri = Delaunay(pts)

# extract all edges:
si_idx = [[0, 1], [0, 2], [1, 2]]  # edge indeces in tri.simplices
edges = [si[i] for si, i in product(tri.simplices, si_idx)]
dist_edges = [np.linalg.norm(tri.points[ii[0]] - tri.points[ii[1]])
              for ii in edges]  # calculate distances

# list points which are closer than eps:
for ee, d in zip(edges, dist_edges):
    if d < eps:
        print("|p[{}] - p[{}]| = {}".format(ee[0], ee[1], d))

正如@David Wolever已经指出的那样,从你的问题中不清楚如何从合并列表中删除点。