Search code examples
pythonnumpyrangeinfinitebin

Numpy: use bins with infinite range


In my Python script I have floats that I want to bin. Right now I'm doing:

min_val = 0.0
max_val = 1.0
num_bins = 20
my_bins = numpy.linspace(min_val, max_val, num_bins)
hist,my_bins = numpy.histogram(myValues, bins=my_bins)

But now I want to add two more bins to account for values that are < 0.0 and for those that are > 1.0. One bin should thus include all values in ( -inf, 0), the other one all in [1, inf)

Is there any straightforward way to do this while still using numpy's histogram function?


Solution

  • The function numpy.histogram() happily accepts infinite values in the bins argument:

    numpy.histogram(my_values, bins=numpy.r_[-numpy.inf, my_bins, numpy.inf])
    

    Alternatively, you could use a combination of numpy.searchsorted() and numpy.bincount(), though I don't see much advantage to that approach.