0

This post is an extension of this question.

I would like to delete multiple elements from a numpy array that have certain values. That is for

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

How do I delete one instance of each value of [1,5,8], such that the output is [1,2,6,8,8,9]. All I have found in the documentation for an array removal is the use of np.setdiff1d, but this removes all instances of each number. How can this be updated?

2

2 Answers 2

1

Using outer comparison and argmax to only remove once. For large arrays this will be memory intensive, since the created mask has a.shape * r.shape elements.


r = np.array([1, 5, 8])
m = (a == r[:, None]).argmax(1)
np.delete(a, m)

array([1, 2, 6, 8, 8, 9])

This does assume that each value in r appears in a at least once, otherwise the value at index 0 will get deleted since argmax will not find a match, and will return 0.

Sign up to request clarification or add additional context in comments.

6 Comments

I don't understand the notation used to define m. Could you explain that?
It's just broadcasted comparison to compare row-wise each value in r with all of array a.
Is it more efficient to use this approach as opposed to LampToasts approach?
Time it on your data, but it should be much faster.
There's no performance difference. They're functionally identical
|
1
delNums = [np.where(a == x)[0][0] for x in [1,5,8]]
a = np.delete(a, delNums)

here, delNums contains the indexes of the values 1,5,8 and np.delete() will delete the values at those specified indexes

OUTPUT:

[1 2 6 8 8 9]

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.