NumPy 1D array slicing

I have a NumPy array, for example:

a = np.array([1,2,3,4,0,0,5,6,7,8,0,0,9,10,11,12])

What is the most efficient way to select all values ​​except values ​​(in my example - 0) in some positions?

So I need to get an array:

[1,2,3,4,5,6,7,8,9,10,11,12]

I know how to skip a single nth value with a construct [::n], but is it possible to skip multiple values ​​using the same syntax?

Thanks for the help!

+4
source share
4 answers

You probably want np.delete:

>>> np.delete(a, [4, 5, 10, 11])
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])
+4
source

You can use Boolean array indexing :

import numpy as np
a = np.array([1,2,3,4,0,0,5,6,7,8,0,0,9,10,11,12])
print a[a != 0]
# Output: [ 1  2  3  4  5  6  7  8  9 10 11 12]

and you can change a != 0to other conditions that lead to a boolean array.

+1

:

>>> a = np.array([1,2,3,4,0,0,5,6,7,8,0,0,9,10,11,12])
>>> a[a != 0]
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])
+1

:

  • , :

    import numpy as np
    
    #your input
    a = np.array([1,2,3,4,0,0,5,6,7,8,0,0,9,10,11,12])
    #indices of elements that you want to remove (given)
    idx = [4,5,10,11]
    #get the inverted indices
    idx_inv = [x for x in range(len(a)) if x not in idx]
    a[idx_inv]
    

    :

    array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])
    
  • np.delete:

    import numpy as np
    
    #your input
    a = np.array([1,2,3,4,0,0,5,6,7,8,0,0,9,10,11,12])
    #indices of elements that you want to remove (given)
    idx = [4,5,10,11]
    
    np.delete(a,idx)
    

    :

    array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])
    
+1

All Articles