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>Reshape the array to multiple rows of five columns then take (slice) the first two columns of each row.</p>

<pre><code>&gt;&gt;&gt; x
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])
&gt;&gt;&gt; x.reshape(x.shape[0] / 5, 5)[:,:2]
array([[ 1,  2],
       [ 6,  7],
       [11, 12]])
</code></pre>

<p>Or</p>

<pre><code>&gt;&gt;&gt; x.reshape(x.shape[0] / 5, 5)[:,:2].flatten()
array([ 1,  2,  6,  7, 11, 12])
&gt;&gt;&gt; 
</code></pre>

<p>It only works with 1-d arrays that have a length that is a multiple of five.</p>

python numpy vectorization