Skip to content Skip to sidebar Skip to footer

Delete An Element Of Certain Value In Numpy Array Once

I would like to delete an element from a numpy array that has a certain value. However, in the case there are multiple elements of the same value, I only want to delete one occurre

Solution 1:

You can simply choose one of the indices:

In [3]: np.delete(a, np.where(a == 8)[0][0])
Out[3]: array([1, 1, 2, 6, 8, 8, 9])

Solution 2:

If you know there is at least one 8 you can use argmax:

np.delete(a,(a==8).argmax())
# array([1, 1, 2, 6, 8, 8, 9])

If not you can still use this method but you have to do one check:

idx=(a==8).argmax()ifa[idx]==8:result=np.delete(a,idx)else:# no 8 in a# complain

Post a Comment for "Delete An Element Of Certain Value In Numpy Array Once"