ndarray delete rows by indexes from condition in another array

Viewed 85

I have two ndarrays, where the length of the first dimension of X is the same as the size of y:

X = np.asarray([[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9],
                [3, 6, 1]])

y = np.asarray([1, 0, 2, 3])

and I have a list:

l = [0, 2, 7]

I want to delete every row from X , if the value of row of the same index from y is in l. So in that case, I will have:

X = np.asarray([[1, 2, 3],
                [3, 6, 1]])

That is because the 2nd and 3rd elements from y - are in l. Therefore, the 2nd and 3rd rows should be deleted from X. How can it be done?

1 Answers

A simple one-liner solution would be using delete and argwhere

X = np.delete(X, np.argwhere(np.isin(y, l)).flatten(), axis=0)

Output

array([[1, 2, 3],
       [3, 6, 1]])
Related