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

查看:21
本文介绍了带容差的 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

我们可以使用广播 -

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天全站免登陆