0

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?

1
  • 1
    You can use Using np.where and a simple indexing. You'll find a lot of similar question in SO if you search thoroughly. (np.where(a==-1) and a[a != -1]) Commented Nov 5, 2017 at 11:40

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0
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

Comments

0

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.