0

I have two numpy ndarrays of the same shape.

A = [[12, 25, 6],
    [28, 52, 74]]
B = [[100, 2, 4],
    [2, 12, 14]]

My goal is to replace every element where there the value in B is <= 5 by 0 in A. So my result should be :

# So C[0][0] = 12 because A[0][0] = 12 and B[0][0] >= 5
C = [[12, 0, 0],
    [0, 52, 74]]

Is there an efficient way to do this? For context, this is to try to do some background substraction on images, and replace all background by black color.

1
  • np.where(B>5, A, 0)? Commented Oct 19, 2021 at 15:27

2 Answers 2

3

Here you go:

A = np.array([[12, 25, 6],[28, 52, 74]])
B = np.array([[100, 2, 4],[2, 12, 14]])

A = np.where(B <= 5, 0, A)

Output:

array([[12,  0,  0],
       [ 0, 52, 74]])
Sign up to request clarification or add additional context in comments.

1 Comment

I think this is reasonable if you're creating a new array, but if you're going to clobber A then A[B <= 5] = 0 seems neater. But then I find np.where() a bit unintuitive.
0

If you want a new array, I would do this:

C = A.copy()
C[B <= 5] = 0

It's a bit faster than np.where() on my machine anyway.

If you don't mind overwriting A, just do A[B <= 5] = 0.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.