Python function that identifies if the numbers in a list or array are closer to 0 or 1
A straightforward way:
lst=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]closerTo1 = [x >= 0.5 for x in lst]
Or you can use np:
import numpy as nplst=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]arr = np.array(lst)closerTo1 = arr >= 0.5
Note that >= 0.5
can be changed to > 0.5
, however you choose to treat it.
numpy.rint
is a ufunc that will round the elements of an array to the nearest integer.
>>> a = np.arange(0, 1.1, 0.1)>>> aarray([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])>>> np.rint(a)array([0., 0., 0., 0., 0., 0., 1., 1., 1., 1., 1.])
What if the numbers don't have to be between 0 and 1?
In that case, I'd use numpy.where
.
>>> a = np.arange(-2, 2.1, 0.1)>>> aarray([-2.00000000e+00, -1.90000000e+00, -1.80000000e+00, -1.70000000e+00, -1.60000000e+00, -1.50000000e+00, -1.40000000e+00, -1.30000000e+00, -1.20000000e+00, -1.10000000e+00, -1.00000000e+00, -9.00000000e-01, -8.00000000e-01, -7.00000000e-01, -6.00000000e-01, -5.00000000e-01, -4.00000000e-01, -3.00000000e-01, -2.00000000e-01, -1.00000000e-01, 1.77635684e-15, 1.00000000e-01, 2.00000000e-01, 3.00000000e-01, 4.00000000e-01, 5.00000000e-01, 6.00000000e-01, 7.00000000e-01, 8.00000000e-01, 9.00000000e-01, 1.00000000e+00, 1.10000000e+00, 1.20000000e+00, 1.30000000e+00, 1.40000000e+00, 1.50000000e+00, 1.60000000e+00, 1.70000000e+00, 1.80000000e+00, 1.90000000e+00, 2.00000000e+00])>>> np.where(a <= 0.5, 0, 1)array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
Here is one simple way to do this:
>>> a = np.arange(-2, 2.1, 0.1)>>> (a >= .5).astype(np.float)array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
(Change np.float
to np.int
if you want integers.)