Binning of data along one axis in numpy
<p>I have a large two dimensional array <code>arr</code> which I would like to bin over the second axis using numpy. Because <code>np.histogram</code> flattens the array I'm currently using a for loop:</p>

<pre><code>import numpy as np

arr = np.random.randn(100, 100)

nbins = 10
binned = np.empty((arr.shape[0], nbins))

for i in range(arr.shape[0]):
    binned[i,:] = np.histogram(arr[i,:], bins=nbins)[0]
</code></pre>

<p>I feel like there should be a more direct and more efficient way to do that within numpy but I failed to find one.</p>

<p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.apply_along_axis.html" rel="nofollow"><code>np.apply_along_axis</code></a>:</p>

<pre><code>x = np.array([range(20), range(1, 21), range(2, 22)])

nbins = 2
&gt;&gt;&gt; np.apply_along_axis(lambda a: np.histogram(a, bins=nbins)[0], 1, x)
array([[10, 10],
       [10, 10],
       [10, 10]])
</code></pre>

<p>The main advantage (if any) is that it's slightly shorter, but I wouldn't expect much of a performance gain. It's possibly marginally more efficient in the assembly of the per-row results.</p>

python numpy histogram binning