[Numpy-discussion] Slicing a numpy array and getting the "complement"
Mon May 19 11:20:22 CDT 2008
2008/5/19 Orest Kozyar <firstname.lastname@example.org>:
> Given a slice, such as s_[..., :-2:], is it possible to take the
> complement of this slice? Specifically, s_[..., ::-2]. I have a
> series of 2D arrays that I need to split into two subarrays via
> slicing where the members of the second array are all the members
> leftover from the slice. The problem is that the slice itself will
> vary, and could be anything such as s_[..., 1:4:] or s_[..., 1:-4:],
> etc, so I'm wondering if there's a straightforward idiom or routine in
> Numpy that would facilitate taking the complement of a slice? I've
> looked around the docs, and have not had much luck.
If you are using boolean indexing, of course complements are easy
(just use ~). But if you want slice indexing, so that you get views,
sometimes the complement cannot be expressed as a slice: for example:
A = np.arange(10)
The complement of A[2:4] is np.concatenate((A[:2],A[4:])). Things
become even more complicated if you start skipping elements.
If you don't mind fancy indexing, you can convert your index arrays
into boolean form:
complement = A==A
complement[idx] = False
More information about the Numpy-discussion