Search code examples
pythonnumpydigitization

Digitizing value to "floor" bin python


I need to digitize some values such that the index returned is the "floor" or "ceiling" bin.

E.g., for bins = numpy.array([0.0, 0.5, 1.0, 1.5, 2.0]) and a value 0.2 I expect the index to be 0, for a value 0.26 the index returned should be 1, and so on.

I have the following ugly looking function to do what I want:

import numpy

def get_bin_index(value, bins):
    bin_diff = bins[1]-bins[0]
    index = numpy.digitize(value, bins)
    if bins[index] - value > bin_diff/2.0:
        index -= 1
    return index

Is there any neat (read better/efficient) way to do this?


Edit: Including timing values (just satisfying my curiosity!)

In [1]: def get_bin_index(value, bins):
    ...:     bin_diff = bins[1]-bins[0]
    ...:     index = numpy.digitize(value, bins)
    ...:     if bins[index] - value > bin_diff/2.0:
    ...:         index -= 1
    ...:     return index
    ...:

In [2]: def get_bin_index_c(value, bins):
    ...:     return numpy.rint((value-bins[0])/(bins[1]-bins[0]))
    ...:

In [3]: def get_bin_index_mid_digitized(value, bins):
    ...:     return numpy.digitize(0.6, (bins[1:] + bins[:-1])/2.0)
    ...:

In [4]: bin_halfs = numpy.array([0.0, 0.5, 1.0, 1.5, 2.0])

In [5]: %timeit get_bin_index(0.9, bin_halfs)
The slowest run took 5.71 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 4.93 µs per loop

In [6]: %timeit get_bin_index_c(0.9, bin_halfs)
The slowest run took 14.60 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 2.34 µs per loop

In [7]: %timeit get_bin_index_mid_digitized(0.9, bin_halfs)
The slowest run took 4.09 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 8.37 µs per loop

Solution

  • If the bin_diffs are all the same, you can do this in constant time by:

    def get_bin_index2(value, bins):
        return numpy.rint((value - bins[0])/(bins[1]-bins[0]))