+1 vote

Best answer

The **digitize()** function of the Numpy module returns the indices of the bins to which each element of an input array belongs.

Here is an example to show how to use this function:

>>> import numpy as np

>>> bins = [0, 0.3, 0.6, 0.9, 1]

>>> a=[random.random() for _ in range(5)]

>>> a

[0.7241728528056117, 0.9554118020610317, 0.6996522756699897, 0.3270152713938511, 0.350725384946479]>>> np.digitize(a,bins,right=False)

array([3, 4, 3, 2, 2])

In the above example, I have mentioned *right=False*, so the bin index will be assigned as follows:

0 <= x < 0.3 ---> 1st bin

0.3 <= x < 0.6 ---> 2nd bin

0.6 <= x < 0.9 ---> 3rd bin

0.9 <= x < 1 ---> 4th bin

The output shows that the first element, "0.7241728528056117," is in the 3rd bin, the second element is in the 4th bin, and so on.