Ad

Numpy Arrays; How To Replace Elements With Another Array Based On Conditions?

- 1 answer

Given two numpy arrays:

import numpy as np 
A = np.array([[0, 5, 0],
             [1, 0, 1],
             [0, 2, 0]])

B = np.array([[0, 7, 0],
             [1, 0, 1],
             [0, 1, 0]])

How can I replace elements in A where the same i,j index is greater in B.

I would have thought that this:

A[A < B] = B

Would work, but it doesn't.

Expected result:

[[0, 7, 0],
 [1, 0, 1],
 [0, 2, 0]]
Ad

Answer

A[A < B] has a very different shape than B, so you can't do that assignment. You wanted to do

A[A < B] = B[A < B]

A bit more efficiently, you could say

mask = A < B
A[mask] = B[mask]

Or you could just evaluate the maximum for each element:

A = np.maximum(A, B)
Ad
source: stackoverflow.com
Ad