metron
metron

Reputation: 201

Deleting the indices in Array

I have the following code for deleting the indices inside the array, but it seems not to work

import numpy as np
length=4
indices=np.arange(length)
for num in (indices):
        np.delete(indices, num)
        print("checking", indices, num)

What seems to be the issue? does np.delete not work on arrays?

Upvotes: 0

Views: 148

Answers (3)

dspr
dspr

Reputation: 2423

It's better not iterating a container while changing its length. Try working with indexed instead :

import numpy as np
length=4
indices=np.arange(length)
for i in reversed(range(len(indices))):
        indices = np.delete(indices, i)
        print("checking", indices, i)

If you're looking for deletion by element you could find the element index before using delete :

import numpy as np
length=4
elements=np.array([1, 3, 2, 4])
for i in elements:
        idx = np.where(elements == i)
        elements = np.delete(elements, idx)
        print("checking", elements, i)

Upvotes: 1

Egor Dementyev
Egor Dementyev

Reputation: 68

numpy.delete returns a copy of given array, it doesn't modify existing one.

Upvotes: 1

Ananth
Ananth

Reputation: 797

Numpy array is immutable. So you cannot delete an item from it. However, you can construct a new array without the values you don't want, like this:

new_indices = np.delete(indices, [0,1,2])

In your code, you can try to get new array after deleting the element, by assigning it to a variable as below:

new_indices = np.delete(indices, num)
print(new_indices, indices) # prints [1,2,3],[0,1,2,3]

Now if you print new_indices it will not have the element at index num

Upvotes: 1

Related Questions