numpy.subtract,直到差值达到阈值-将小于阈值的数替换为阈值
我想从我的 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
1 个回答
2
向量化的方法通常在使用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])