numpy binning: how to get array indexes satisfying a predicate
<p>I have a vector <code>g</code> of values of length 1024 and a smaller vector <code>f</code> of size 32 defining bin boundaries. <code>v</code> and <code>f</code> are sorted in ascending order. I want to return an array of vectors i.e <code>[v_1,v_2,v_3,...]</code> of length <code>len(f)</code> such that each vector <code>v_i</code> contains indices of <code>g</code> between <code>f_i</code> and <code>f_i + 1</code>. Is there a NumPy way to do such a thing that does not involve looping?</p>

<p>first things first:</p>

<pre><code>import numpy as np
</code></pre>

<p>let's say you have your data <code>g</code>:</p>

<pre><code>g = sorted((1e3 * np.random.random(1024)).astype(int))
</code></pre>

<p>and your bins <code>f</code>:</p>

<pre><code>f = sorted((1e3 * np.random.random(32)).astype(int))
</code></pre>

<p>you can use <code>numpy.digitize</code>, which return the bin indices in <code>f</code> where each element of <code>g</code> belongs:</p>

<pre><code>dg = np.digitize(g,f)
</code></pre>

<p>The resulting vector is going to contains list of different sizes so you might want to store it is a list:</p>

<pre><code>for i in range(len(f)): v.append(np.argwhere(dg == i))
</code></pre>

python numpy