我有两个NumPy数组:
A= [ 3.8357 3.2450]
B= [ 5.6132 3.2415 3.6086 3.5666 3.8769 4.3587]
我想比较A和B,并仅保留在A中唯一的值,但要在±0.04的容差范围之外(例如,A=[3.8357])。
你有什么好的想法吗?
我有两个NumPy数组:
A= [ 3.8357 3.2450]
B= [ 5.6132 3.2415 3.6086 3.5666 3.8769 4.3587]
我想比较A和B,并仅保留在A中唯一的值,但要在±0.04的容差范围之外(例如,A=[3.8357])。
你有什么好的想法吗?
方法#1
我们可以使用broadcasting
-
A[(np.abs(np.subtract.outer(A,B)) > 0.04).all(1)]
方法 #2
我们可以利用searchsorted
,来实现具有公差规范的通用numpy.isin
,以便在通用问题中使用,如下所示 -
def isin_tolerance(A, B, tol):
A = np.asarray(A)
B = np.asarray(B)
Bs = np.sort(B) # skip if already sorted
idx = np.searchsorted(Bs, A)
linvalid_mask = idx==len(B)
idx[linvalid_mask] = len(B)-1
lval = Bs[idx] - A
lval[linvalid_mask] *=-1
rinvalid_mask = idx==0
idx1 = idx-1
idx1[rinvalid_mask] = 0
rval = A - Bs[idx1]
rval[rinvalid_mask] *=-1
return np.minimum(lval, rval) <= tol
out = A[~isin_tolerance(A, B, tol=0.04)]
示例运行:
In [294]: A
Out[294]: array([13.8357, 3.245 , 3.8357])
In [295]: B
Out[295]: array([5.6132, 3.2415, 3.6086, 3.5666, 3.8769, 4.3587])
In [296]: A[~isin_tolerance(A, B, tol=0.04)]
Out[296]: array([13.8357, 3.8357])