具有公差的NumPy setdiff1d-将numpy数组与另一个数组进行比较,并且仅保存唯一值-超出公差 [英] NumPy setdiff1d with tolerance - Comparing a numpy array to another and saving only the unique values - outside of a tolerance

查看:69
本文介绍了具有公差的NumPy setdiff1d-将numpy数组与另一个数组进行比较,并且仅保存唯一值-超出公差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个numpy数组:

I have two numpy arrays:

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]).

I want to compare A to B and only keep the value in A that is unique - outside of a +/-0.04 tolerance (i.e. A=[3.8357]).

关于如何执行此操作的任何想法?

Any ideas as to how I can do this?

推荐答案

方法1

我们可以使用 broadcasting -

We could use broadcasting -

A[(np.abs(np.subtract.outer(A,B)) > 0.04).all(1)]

方法2

我们可以利用 searchsorted 具有通用的 numpy.isin 与公差说明符一起用于一般性问题,例如-

We could leverage searchsorted to have a generic numpy.isin with tolerance specifier for use in generic problems, like so -

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

因此,要解决我们的问题-

Hence, to solve our case -

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])

这篇关于具有公差的NumPy setdiff1d-将numpy数组与另一个数组进行比较,并且仅保存唯一值-超出公差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆