Suppose you have a numpy array(n,n) ie.
x = np.arange(25).reshape(5,5)
and you fill x with random integers between -5 and 5. Is there a method to use a boolean mask so that all of my values which are 0 become 1 and all my numbers which are nonzero become zero?(i.e, if [index]>0 or [index]<0, [index]=0, and if [index]=0 then [index]=1)
I know you could use an iteration to change each element, but my goal is speed and as such I would like to eliminate as many loops as possible from the finalized script.
EDIT: Open to other ideas, as well, of course, as long as speed/efficiency is kept in mind
Firstly, you could instantiate your array directly using np.random.randint
:
# Note: the lower limit is inclusive while the upper limit is exclusive
x = np.random.randint(-5, 6, size=(5, 5))
To actually get the job done, perhaps type-cast to bool, type-cast back, and then negate?
res = 1 - x.astype(bool).astype(int)
Alternatively, you could be a bit more explicit:
x[x != 0] = 1
res = 1 - x
But the second method seems to take more than twice as much time:
>>> n = 1000
>>> a = np.random.randint(-5, 6, (n, n))
>>> %timeit a.astype(bool).astype(int)
1000 loops, best of 3: 1.58 ms per loop
>>> %timeit a[a != 0] = 1
100 loops, best of 3: 4.61 ms per loop