Sid
Sid

Reputation: 286

Delete array of values from numpy array

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?

Upvotes: 0

Views: 130

Answers (2)

user3483203
user3483203

Reputation: 51165

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.

Upvotes: 1

LampToast
LampToast

Reputation: 553

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]

Upvotes: 1

Related Questions