Issue
Lets say i have a numpy Array where i would like to swap all the 1's to 0 and all the 0's to a 1 (the array will have other values, and there is nothing special about the 0's and 1's). Ofcourse i can loop through the array and change it 1 by 1. Is there an efficient method you can recommend using? does the np.where() method have an option for this operation?
Solution
A very simple way which does not require the use of any special method such as np.where()
is to get the indices for the conditions of the variables in your numpy
array, and accordingly assign the required value (in your case 0
for 1s
and 1
for 0s
) to the respective positional items in the array. This works for values other than 0s
and 1s
too. Also, you don't require any temporary variable to swap the values.
import numpy as np
arr = np.array([1, 0, 2, 3, 6, 1, 0])
indices_one = arr == 1
indices_zero = arr == 0
arr[indices_one] = 0 # replacing 1s with 0s
arr[indices_zero] = 1 # replacing 0s with 1s
Output: array([0, 1, 2, 3, 6, 0, 1])
Answered By - JChat
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.