Home > Back-end >  How to change all elements in the array to 1 or zero if odd or even
How to change all elements in the array to 1 or zero if odd or even

Time:10-19

I have a NumPy array and I need to change the values to 0 if odd, 1 if even. How can I do that?

arr  = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

CodePudding user response:

The modulo operator is useful here:

arr % 2

This results in 1 everywhere you have an odd number (because there's a remainder of 1 under integer division by 2), which is the opposite of what you want.

To flip it, substract it from 1:

1 - arr % 2

On your data, this gives:

array([[0, 1, 0, 1, 0],
       [1, 0, 1, 0, 1]])

Note that this doesn't actually change your input data, which is what you asked for. You could achieve that by overwriting arr with this result.

  • Related