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>

<pre><code>import numpy as np

x = np.array(range(1, 16))
y = np.vstack([x[0::5], x[1::5]]).T.ravel()
y
// =&gt; array([ 1,  2,  6,  7, 11, 12])
</code></pre>

<p>Taking the first <code>N</code> rows of every block of <code>M</code> rows in the array <code>[1, 2, ..., K</code>]:</p>

<pre><code>import numpy as np

K = 30
M = 5
N = 2

x = np.array(range(1, K+1))
y = np.vstack([x[i::M] for i in range(N)]).T.ravel()
y
// =&gt; array([ 1,  2,  6,  7, 11, 12, 16, 17, 21, 22, 26, 27])
</code></pre>

<p>Notice that <code>.T</code> and <code>.ravel()</code> are fast operations: they don't copy any data, but just manipulate the dimensions and strides of the array.</p>

<p>If you insist on getting your slice using fancy indexing:</p>

<pre><code>import numpy as np

K = 30
M = 5
N = 2

x = np.array(range(1, K+1))
fancy_indexing = [i*M+n for i in range(len(x)//M) for n in range(N)]
x[fancy_indexing]
// =&gt; array([ 1,  2,  6,  7, 11, 12, 16, 17, 21, 22, 26, 27])
</code></pre>

python numpy vectorization