Wellington Júnior Wellington Júnior - 4 months ago 8
Python Question

Error with multiple numpy.delete uses on array?

So, I was trying to understand the

numpy.delete
function, and I came up with something weird. Here's the program:

>>>import numpy as np
>>>a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 6, 7, 9])
>>> a[5]
5
>>> a=np.delete(a,[a[5]])
>>> a
array([0, 1, 2, 3, 4, 6, 7, 8, 9]) #so far so good
>>> a[6]
7
>>> a=np.delete(a,[a[6]])
>>> a
array([0, 1, 2, 3, 4, 6, 7, 9])


So... When I put
a=np.delete(a,[a[6]])
, it should be expected to remove the number
7
from the array, right? Why was it the number
8
(the term
a[7]
) from the array) removed instead of the expected
a[6]
?

I also noticed that when I try to remove the
a[0]
(=0) from the array after the first delete, I just can't. It always removes one term ahead. Any Idea how do I remove it?

Answer

The second argument should be the index of the element you want to delete, not the element itself.

a=np.delete(a,6)

In the first case, it only worked because a[5] happened to equal 5, so the index and the value were the same.

When you have:

a=np.delete(a,[a[6]])

You are deleting the 7th element since a[6] = 7 there.

Comments