简体   繁体   中英

Python element-wise condition on numpy ndarray

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.

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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