How do I split an ndarray based on array of indexes? How do I split an ndarray based on array of indexes? numpy numpy

How do I split an ndarray based on array of indexes?


Sorry, so you already have take and basically need the opposite of take, you can get that with some indexing nicely:

a = np.arange(16).reshape((8,2))b = [2, 6, 7]mask = np.ones(len(a), dtype=bool)mask[b,] = Falsex, y = a[b], a[mask] # instead of a[b] you could also do a[~mask]print xarray([[ 4,  5],       [12, 13],       [14, 15]])print yarray([[ 0,  1],       [ 2,  3],       [ 6,  7],       [ 8,  9],       [10, 11]])

So you just create a boolean mask that is True wherever b would not select from a.


There is actually already np.split which handles this (its pure python code, but that should not really bother you):

>>> a = np.arange(16).reshape((8,2))>>> b = [2, 6]>>> print np.split(a, b, axis=0) # plus some extra formatting[array([[0, 1],       [2, 3]]), array([[ 4,  5],       [ 6,  7],       [ 8,  9],       [10, 11]]), array([[12, 13],       [14, 15]])]

split always includes the slice from 0:b[0] and b[0]:, I guess you can just slice them out of the results for simplicity. If you have regular splits of course (all the same size), you may just be better of with using reshape.

Note also that this returns views. So if you change those arrays you change the original unless you call .copy first.