np.where
np.where(a > 0.5, 1, 0)
# array([0, 0, 0, 1, 1, 1])
Boolean basking with astype
(a > .5).astype(int)
# array([0, 0, 0, 1, 1, 1])
np.select
np.select([a <= .5, a>.5], [np.zeros_like(a), np.ones_like(a)])
# array([ 0., 0., 0., 1., 1., 1.])
Special case: np.round
This is the best solution if your array values are floating values between 0 and 1 and your threshold is 0.5.
a.round()
# array([0., 0., 0., 1., 1., 1.])
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…