根据与点的距离过滤坐标 [英] Filtering coordinates based on distance from a point
问题描述
我有两个数组说:
A = np.array([[ 1. , 1. , 0.5 ],
[ 2. , 2. , 0.7 ],
[ 3. , 4. , 1.2 ],
[ 4. , 3. , 2.33],
[ 1. , 2. , 0.5 ],
[ 6. , 5. , 0.3 ],
[ 4. , 5. , 1.2 ],
[ 5. , 5. , 1.5 ]])
B = np.array([2,1])
我想找到 A
的所有值,这些值不在 B
的半径 2 之内.
I would want to find all values of A
which are not within a radius of 2 from B
.
我的答案应该是:
C = [[3,4,1.2],[4,3,2.33],[6,5,0.3],[4,5,1.2],[5,5,1.5]]
有没有pythonic的方法来做到这一点?
Is there a pythonic way to do this?
我尝试过的是:
radius = 2
C.append(np.extract((cdist(A[:, :2], B[np.newaxis]) > radius), A))
但是我意识到 np.extract
会压平 A
并且我没有得到预期的结果.
But I realized that np.extract
flattens A
and i dont get what i is expected.
推荐答案
让 R
成为这里的半径.如下文所述,我们几乎没有办法解决它.
Let R
be the radius here. We would have few methods to solve it, as discussed next.
方法 1: 使用 cdist
-
from scipy.spatial.distance import cdist
A[(cdist(A[:,:2],B[None]) > R).ravel()]
方法 #2: 使用 np.einsum
-
d = A[:,:2] - B
out = A[np.einsum('ij,ij->i', d,d) > R**2]
方法 #3: 使用 np.linalg.norm
-
A[np.linalg.norm(A[:,:2] - B, axis=1) > R]
方法 #4: 使用 matrix-multiplication
和 np.dot
-
Approach #4 : Using matrix-multiplication
with np.dot
-
A[(A[:,:2]**2).sum(1) + (B**2).sum() - 2*A[:,:2].dot(B) > R**2]
方法 #5: 结合使用 einsum
和 matrix-multiplication
-
Approach #5 : Using a combination of einsum
and matrix-multiplication
-
A[np.einsum('ij,ij->i',A[:,:2],A[:,:2]) + B.dot(B) - 2*A[:,:2].dot(B) > R**2]
方法#6:使用广播
-
A[((A[:,:2] - B)**2).sum(1) > R**2]
因此,要获得半径 R
内的点,只需将上述解决方案中的 >
替换为 <
.
Hence, to get the points within radius R
simply replace >
with <
in the above mentioned solutions.
这篇关于根据与点的距离过滤坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!