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>I first thought you need this to work for 2d arrays due to your phrasing of "first N rows of every block of M rows", so I'll leave my solution as this.</p>

<p>You could work some magic by reshaping your array into 3d:</p>

<pre><code>M = 5 # size of blocks
N = 2 # number of columns to cut
x = np.arange(3*4*M).reshape(4,-1) # (4,3*N)-shaped dummy input
x = x.reshape(x.shape[0],-1,M)[:,:,:N+1].reshape(x.shape[0],-1) # (4,3*N)-shaped output
</code></pre>

<p>This will extract every column according to your preference. In order to use it for your 1d case you'd need to make your 1d array into a 2d one using <code>x = x[None,:]</code>.</p>

python numpy vectorization