简体   繁体   English

根据条件用另一个Numpy 2D数组的相应元素替换Numpy 2D数组中的元素

[英]Replacing elements in Numpy 2D array with corresponding elements of another Numpy 2D array depending on a condition

I am new to Numpy and I was wondering if there is a fast way to replace elements in a 2D array (lets call it "A") that are meeting a specific condition with their corresponding elements of another 2D array (lets call it "B"), and at the same time keep the values of the remaining elements in array "A" that didn't meet this condition; 我是Numpy的新手,我想知道是否存在一种快速方法来将满足特定条件的2D数组(称为“ A”)中的元素替换为另一个2D数组的相应元素(称为“ B”) “”,同时将不满足此条件的其余元素的值保留在数组“ A”中; I should mention that "B" has the same shape as "A". 我应该提到“ B”与“ A”具有相同的形状。

Thanks a lot in advance 提前谢谢

Say the condition is element < 2 . 说条件是element < 2 Then we can create a mask indicating which cells match the condition: 然后我们可以创建一个掩码,指示哪些单元格符合条件:

mask = A < 2

and use advanced indexing to select the corresponding elements of B and assign their values to the corresponding cells of A : 并使用高级索引选择B的相应元素,并将其值分配给A的相应单元格:

A[mask] = B[mask]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM