Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 646
Ricky Robinson Avatar asked Jul 24 '12 15:07

Ricky Robinson


2 Answers

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.

like image 164
Sven Marnach Avatar answered Oct 10 '22 19:10

Sven Marnach


You can specify numpy.inf as the upper and -numpy.inf as the lower bin limits.

like image 29
jmetz Avatar answered Oct 10 '22 18:10

jmetz