Python: Assigning # values in a list to bins, by rounding up
<p>I want a function that can take a series and a set of bins, and basically round up to the nearest bin. For example:</p>

<pre><code>my_series = [ 1, 1.5, 2, 2.3,  2.6,  3]
def my_function(my_series, bins):
    ...

my_function(my_series, bins=[1,2,3])
&gt; [1,2,2,3,3,3]
</code></pre>

<p>This seems to be very close to what <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html" rel="nofollow">Numpy's Digitize</a> is intended to do, but it produces the wrong values (asterisks for wrong values):</p>

<pre><code>np.digitize(my_series, bins= [1,2,3], right=False)
&gt; [1, 1*, 2, 2*, 2*, 3]
</code></pre>

<p>The reason why it's wrong is clear from the documentation:</p>

<blockquote>
  <p>Each index i returned is such that <strong>bins[i-1] &lt;= x &lt; bins[i]</strong> if bins is
  monotonically increasing, or <strong>bins[i-1] > x >= bins[i]</strong> if bins is
  monotonically decreasing. If values in x are beyond the bounds of
  bins, 0 or len(bins) is returned as appropriate. If right is True,
  then the right bin is closed so that the index i is such that
  bins[i-1] &lt; x &lt;= bins[i] or bins[i-1] >= x > bins[i]`` if bins is
  monotonically increasing or decreasing, respectively.</p>
</blockquote>

<p>I can kind of get closer to what I want if I enter in the values decreasing and set "right" to True... </p>

<pre><code>np.digitize(my_series, bins= [3,2,1], right=True)
&gt; [3, 2, 2, 1, 1, 1]
</code></pre>

<p>but then I'll have to think of a way of basically methodically reversing the lowest number assignment (1) with the highest number assignment (3). It's simple when there are just 3 bins, but will get hairier when the number of bins get longer..there must be a more elegant way of doing all this.</p>

<p>I believe <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html" rel="nofollow"><code>np.searchsorted</code></a> will do what you want:</p>

<blockquote>
  <p>Find the indices into a sorted array <code>a</code> such that, if the corresponding
  elements in <code>v</code> were inserted before the indices, the order of a would
  be preserved.</p>
</blockquote>

<pre><code>In [1]: my_series = [1, 1.5, 2, 2.3, 2.6, 3]

In [2]: bins = [1,2,3]

In [3]: import numpy as np

In [4]: [bins[k] for k in np.searchsorted(bins, my_series)]
Out[4]: [1, 2, 2, 3, 3, 3]
</code></pre>

<p>(As of numpy 1.10.0, <code>digitize</code> is implemented in terms of <code>searchsorted</code>.)</p>

python numpy grouping rounding bins