1

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]]

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

A simple solution by conditioning B to give a similarly sized array and then setting from its results:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.