Sid
Sid

Reputation: 286

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 occurrence (doesn't matter which one). That is:

import numpy as np
a = np.array([1, 1, 2, 6, 8, 8, 8, 9])

How do I delete one instance of 8? Specifically

a_new = np.delete(a, np.where(a == 8))
print(a_new)

removes all 8's.

Upvotes: 4

Views: 6908

Answers (2)

Paul Panzer
Paul Panzer

Reputation: 53029

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()
if a[idx] == 8:
    result = np.delete(a,idx)
else: # no 8 in a
    # complain

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107287

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

Upvotes: 4

Related Questions