Slicing multiple rows by single index <p>I have the following slicing problem in numpy.</p> <pre><code>a = np.arange(36).reshape(-1,4) a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23], [24, 25, 26, 27], [28, 29, 30, 31], [32, 33, 34, 35]]) </code></pre> <p>In my problem always three rows represent one sample, in my case coordinates.</p> <p>I want to access this matrix in a way that if I use a[0:2] to get the following:</p> <pre><code>array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]] </code></pre> <p>These are the first two coordinate samples. I have to extract a large amount of these coordinate sets from an array.</p> <p>Thanks</p> <p>Based on <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a>, I found the following solution, which gives me the desired result.</p> <pre><code>def chunks(l, n, indices): return np.vstack([l[idx*n:idx*n+n] for idx in indices]) chunks(a,3,[0,2]) array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [24, 25, 26, 27], [28, 29, 30, 31], [32, 33, 34, 35]]) </code></pre> <p>Probably this solution could be improved and somebody won't need the stacking.</p>