I'm trying to use the where method to replace all odd numbers from the below array with a -1
np.array([0, 1, 0, 3, 0, 5, 0, 7, 0, 9])
I've tried using the below, but it's not working.
np.where(Q9 % 2 == 1) = - 1
Thanks for any assistance!
CodePudding user response:
where
method only returns indices
arr = np.array([0, 1, 0, 3, 0, 5, 0, 7, 0, 9])
arr[np.where(arr%2!=0)] = -1
print(arr)
output:
[ 0 -1 0 -1 0 -1 0 -1 0 -1]
CodePudding user response:
If you want to replace in the original array, where
is not needed, use simple indexing:
a = np.array([0, 1, 0, 3, 0, 5, 0, 7, 0, 9])
a[a%2==1] = -1
a
For a new array:
b = np.where(a%2==1, -1, a)
output: array([ 0, -1, 0, -1, 0, -1, 0, -1, 0, -1])