user3479707
user3479707

Reputation: 5

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; I should mention that "B" has the same shape as "A".

Thanks a lot in advance

Upvotes: 0

Views: 775

Answers (1)

user2357112
user2357112

Reputation: 280456

Say the condition is 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:

A[mask] = B[mask]

Upvotes: 4

Related Questions