Efficient numpy indexing: Take first N rows of every block of M rows
<pre><code>x = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])
</code></pre>

<p>I want to grab first 2 rows of array x from every block of 5, result should be:</p>

<pre><code>x[fancy_indexing] = [1,2, 6,7, 11,12]
</code></pre>

<p>It's easy enough to build up an index like that using a for loop.</p>

<p>Is there a one-liner slicing trick that will pull it off? Points for simplicity here.</p>

<p><strong>Approach #1</strong> Here's a vectorized one-liner using <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow"><code>boolean-indexing</code></a> -</p>

<pre><code>x[np.mod(np.arange(x.size),M)&lt;N]
</code></pre>

<p><strong>Approach #2</strong> If you are going for performance, here's another vectorized approach using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.strides.html" rel="nofollow"><code>NumPy strides</code></a> -</p>

<pre><code>n = x.strides[0]
shp = (x.size//M,N)
out = np.lib.stride_tricks.as_strided(x, shape=shp, strides=(M*n,n)).ravel()
</code></pre>

<p>Sample run -</p>

<pre><code>In [61]: # Inputs
    ...: x = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])
    ...: N = 2
    ...: M = 5
    ...: 

In [62]: # Approach 1
    ...: x[np.mod(np.arange(x.size),M)&lt;N]
Out[62]: array([ 1,  2,  6,  7, 11, 12])

In [63]: # Approach 2
    ...: n = x.strides[0]
    ...: shp = (x.size//M,N)
    ...: out=np.lib.stride_tricks.as_strided(x,shape=shp,strides=(M*n,n)).ravel()
    ...: 

In [64]: out
Out[64]: array([ 1,  2,  6,  7, 11, 12])
</code></pre>

python numpy vectorization