4

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.

4
  • Sounds like an xy problem. Why are you trying to delete anything from a numpy array to begin with? Commented Oct 17, 2019 at 10:39
  • It's a pattern matching step. Then I continue with the use of numpy arrays. Commented Oct 17, 2019 at 11:44
  • You reallocate the entire array to delete one element. Sounds like masking might be a better way potentially. Commented Oct 17, 2019 at 12:10
  • That's true. How can masking be used? Commented Oct 17, 2019 at 12:15

2 Answers 2

4

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])
Sign up to request clarification or add additional context in comments.

Comments

1

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

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.