Python function that identifies if the numbers in a list or array are closer to 0 or 1

  • A+
Category:Languages

I have a numpy array of numbers. Below is an example:

[[-2.10044520e-04  1.72314372e-04  1.77235336e-04 -1.06613465e-04 6.76617611e-07  2.71623057e-03 -3.32789944e-05  1.44899758e-05 5.79249863e-05  4.06502549e-04 -1.35823707e-05 -4.13955189e-04 5.29862793e-05 -1.98286005e-04 -2.22829175e-04 -8.88758230e-04 5.62228710e-05  1.36249752e-05 -2.00474996e-05 -2.10090068e-05 1.00007518e+00  1.00007569e+00 -4.44597417e-05 -2.93724453e-04 1.00007513e+00  1.00007496e+00  1.00007532e+00 -1.22357142e-03 3.27903892e-06  1.00007592e+00  1.00007468e+00  1.00007558e+00 2.09869172e-05 -1.97610235e-05  1.00007529e+00  1.00007530e+00 1.00007503e+00 -2.68725642e-05 -3.00372853e-03  1.00007386e+00 1.00007443e+00  1.00007388e+00  5.86993822e-05 -8.69989983e-06 1.00007590e+00  1.00007488e+00  1.00007515e+00  8.81850779e-04 2.03875532e-05  1.00007480e+00  1.00007425e+00  1.00007517e+00 -2.44678912e-05 -4.36556267e-08  1.00007436e+00  1.00007558e+00 1.00007571e+00 -5.42990711e-04  1.45517859e-04  1.00007522e+00 1.00007469e+00  1.00007575e+00 -2.52271817e-05 -7.46339417e-05 1.00007427e+00]] 

I want to know if each of the numbers is closer to 0 or 1. Is there a function in Python that could do it or do I have to do it manually?

 


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) >>> a array([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) >>> a array([-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]) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: