Skip to main content
 首页 » 编程设计

python之numpy.subtract 但直到差异达到阈值之用阈值替换小于该值的数字

2024年10月25日10langtianya

我想从我的 numpy 数组中的每个元素中减去给定的值。 例如,如果我有一个名为 a_q 的 numpy 数组和名为 subtract_me 的变量,那么我可以简单地这样做:

result = np.subtract(a_q,subtract_me) 

没关系。但我不希望它简单地盲目地从每个元素中减去。如果差异低于阈值,那么我不希望减法发生。相反,我希望数组的该元素被该阈值替换。

最有效的方法是什么?我可以简单地遍历数组并从每个元素中减去并检查是否达到阈值,然后根据结果构建一个新数组(如下所示)——但是有没有更好或更有效的方法去做?

threshold = 3 # in my real program, the threshold is the  
              # lowest non-infinity number that python can handle 
subtract_me = 6 
a_q = [] 
for i in range(10): 
    val = i - subtract_me 
    if val < threshold: 
        val = threshold 
    a_q.append(val) 
 
myarr = np.array(a_q) 
print myarr 

请您参考如下方法:

向量化方法通常对 NumPy 数组最有效,因此这里有一种方法可能比一次迭代一个数组的一个元素更有效:

>>> threshold = 3 
>>> subtract_me = 6 
>>> a_q = np.arange(10) 
 
>>> arr = a_q - subtract_me # takeaway the subtract_me value 
array([-6, -5, -4, -3, -2, -1,  0,  1,  2,  3]) 
 
>>> arr[arr - subtract_me < threshold] = threshold # replace any value less than threshold 
array([3, 3, 3, 3, 3, 3, 3, 3, 3, 3]) 

编辑:自 np.clip在问题下方的评论中提到了,为了完整性,我不妨将其吸收到我的答案中;-)

这是您可以使用它获得所需结果的一种方法:

>>> np.clip((a_q - subtract_me), threshold, np.max(a_q)) 
array([3, 3, 3, 3, 3, 3, 3, 3, 3, 3])