1

I have the following slicing problem in numpy.

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]])

In my problem always three rows represent one sample, in my case coordinates.

I want to access this matrix in a way that if I use a[0:2] to get the following:

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]]

These are the first two coordinate samples. I have to extract a large amount of these coordinate sets from an array.

Thanks

Based on How do you split a list into evenly sized chunks?, I found the following solution, which gives me the desired result.

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]])

Probably this solution could be improved and somebody won't need the stacking.

Community
  • 1
  • 1
duga3
  • 37
  • 5
  • possible duplicate of [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) – mhlester Jan 22 '14 at 18:53
  • 2
    Just do this `a[0:2*3]` in general `a[i*3,j*3]` – Alvaro Fuentes Jan 22 '14 at 18:55

1 Answers1

1

If three rows are a sample, you can reshape your array to reflect that, use fancy indexing to retrieve your samples, then undo the shape change:

>>> a = a.reshape(-1, 3, 4)
>>> a[[0, 2]].reshape(-1, 4)
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]])
Jaime
  • 65,696
  • 17
  • 124
  • 159