Reputation: 2079
I have a numpy array with some positive numbers and some -1
elements. I want to find these elements with -1
values, delete them and store their indeces.
One way of doing it is iterating through the array and cheking if the value is -1
. Is this the only way? If not, what about its effectivness? Isn't there a more effective python tool then?
Upvotes: 0
Views: 474
Reputation: 402493
Use a combination of np.flatnonzero
and simple boolean indexing.
x = array([ 0, 0, -1, 0, 0, -1, 0, -2, 0, 0])
m = x != -1 # generate a mask
idx = np.flatnonzero(~m)
x = x[m]
idx
array([2, 5])
x
array([ 0, 0, 0, 0, 0, -2, 0, 0])
Upvotes: 0
Reputation: 92854
With numpy.argwhere()
and numpy.delete()
routines:
import numpy as np
arr = np.array([1, 2, 3, -1, 4, -1, 5, 10, -1, 14])
indices = np.argwhere(arr == -1).flatten()
new_arr = np.delete(arr, indices)
print(new_arr) # [ 1 2 3 4 5 10 14]
print(indices.tolist()) # [3, 5, 8]
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.argwhere.html https://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html
Upvotes: 2
Reputation: 1759
import numpy as np
yourarray=np.array([4,5,6,7,-1,2,3,-1,9,-1]) #say
rangenumpyarray=np.arange(len(yourarray)) # to create a column adjacent to your array of range
arra=np.hstack((rangenumpyarray.reshape(-1,1),yourarray.reshape(-1,1))) # combining both arrays as two columns
arra[arra[:,1]==-1][:,0] # learn boolean indexing
Upvotes: 0