[英]Change values of a 1D numpy array based on certain condition
Very basic question: 很基本的问题:
Suppose I have a 1D numpy array (A) containing 5 elements: 假设我有一个包含5个元素的一维numpy数组(A):
A = np.array([ -4.0, 5.0, -3.5, 5.4, -5.9])
I need to add, 5 to all the elements of A that are lesser than zero. 我需要将A的所有小于零的元素加5。 What is the numpy way to do this without for-looping ? 没有for循环的numpy方法是什么?
It can be done using mask: 可以使用mask来完成:
A[A < 0] += 5
The way it works is - the expression A < 0
returns a boolean array. 它的工作方式是-表达式A < 0
返回一个布尔数组。 Each cell corresponds to the predicate applied on the matching cell. 每个单元格对应于应用于匹配单元格的谓词。 In the current example: 在当前示例中:
A < 0 # [ True False True False True]
And then, the action is applied only on the cells that match the predicate. 然后,该操作仅应用于与谓词匹配的单元格。 So in this example, it works only on the True
cells. 因此,在此示例中,它仅适用于True
单元。
我找到了另一个答案:
A = np.where(A < 0, A + 5, A)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.