pythonnumpyslice

How can I inverse a slice of an array?


I want to do something along the lines of...

import numpy as np

arr = np.linspace(0, 10, 100)
s = slice(1, 10)
print(arr[s])
print(arr[~s])

How could I apply the "not" operator to a slice, so that in this case arr[~s] would be the concatenation of arr[0] and arr[10:]?


Solution

  • np.delete will do what you want:

    np.delete(arr, s)
    

    For something more complex than a slice, you may want to store the index. To do that, you can invert a mask built from the slice:

    mask = np.ones(arr.shape, dtype=bool)
    mask[s] = False
    arr[mask]
    

    OR

    mask = np.zeros(arr.shape, dtype=bool)
    mask[s] = True
    arr[~mask]
    

    You can also use np.delete on an index array:

    arr[np.delete(np.arange(arr.size), s)]
    

    This gets a bit more complex if you have a multidimensional array. For example, you would probably use np.indices instead of np.arange.