Comparing 2 numpy arrays

I have 2 numpy arrays and I want whenever element B is 1, the element in A is equal to 0. Both arrays are always in the same dimension:

A = [1, 2, 3, 4, 5]
B = [0, 0, 0, 1, 0]

I tried to do numpy slicing but I still can't get it to work.

B[A==1]=0

How can I achieve this in numpy without doing the conventional loop ?

Answers


First, you need them to be numpy arrays and not lists. Then, you just inverted B and A.

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

If you use lists instead, here is what you get

A = [1, 2, 3, 4, 5]
B = [0, 0, 0, 1, 0]
A[B==1]=0 ## [0, 2, 3, 4, 5]

That's because B == 1 is False or 0 (instead of an array). So you essentially write A[0] = 0


Isn't it that what you want to do ?

A[B==1] = 0
A
array([1, 2, 3, 0, 5])

Need Your Help

getting result from a function running "deferToThread"

twisted

I have recently started working on twisted not much familiar with its functions.I have a problem related to "deferToThread" method...my code is here to use this method

HTTP 500 Internal Server error when uploading files

php apache http file-upload cpanel

This is driving me crazy. I have a php file upload script hosted on CPanel-controlled web hosting, whenever I try to upload files larger than 3-4 MB I get a HTTP 500 Internal Server Error. Now, I did