I am looking for a fast way to compute the following:
import numpy as np
a = np.array([-1,1,2,-4,5.5,-0.1,0])
Now I want to cast a to an array of binary values such that it has a 1 for every positive entry of a and a 0 otherwise. So the result I want is this:
array([ 0., 1., 1., 0., 1., 0., 0.])
One way to achieve this would be
np.array([x if x >=0 else 0 for x in np.sign(a)])
array([ 0., 1., 1., 0., 1., 0., 0.])
But I am hoping someone can point out a faster solution.
%timeit np.array([x if x >=0 else 0 for x in np.sign(a)])
100000 loops, best of 3: 11.4 us per loop
EDIT: timing the great solutions from the answers
%timeit (a > 0).astype(int)
100000 loops, best of 3: 3.47 us per loop
a > 0might work without converting it to typeintorint8.