2

I have two numpy arrays:

a = np.array([12, 13, 10])
b = np.array([[22, 123], [10, 142], [23, 232], [42, 122], [12, 239]])

I want to delete rows in b if the first element is not in a. Something like:

c = np.delete(b, np.where(a not in b[:, 0]))

print(c) gives:

[ 22 123  10 142  23 232  42 122  12 239]

which doesn't delete an element: c should look like

c = [[10, 142],
     [12, 239]]
2
  • what does a not in b[:,0] produce? And after the np.where? You need to understand, and know, what each step in the expression is doing. Also review what np.delete expects. Commented Mar 16, 2022 at 18:38
  • Those are not numpy arrays... Commented Mar 16, 2022 at 18:45

2 Answers 2

1

Your input:

import numpy as np

a=[12,13,10]
b=[[22, 123],[10,142],[23,232],[42,122],[12,239]]
a, b = np.array(a), np.array(b)

c = b[np.isin(b[:, 0], a)]

Output:

array([[ 10, 142],
       [ 12, 239]])
Sign up to request clarification or add additional context in comments.

Comments

0

You need to mark the rows in b whose first elements are not in a. np.isin returns an array of that masks the first input. It also provides an argument invert, to speed up the inversion that you want:

mask = np.isin(b[:, 0], a, invert=True)

You can use this mask in np.delete directly:

c = np.delete(b, mask, axis=0)

Alternatively, you can convert it to indices using np.flatnonzero:

index = np.flatnonzero(mask)
result = np.delete(b, index, axis=0)

Furthermore, you don't need to use np.delete at all, since indexing with the non-inverted mask will drop the undesired rows:

result = b[np.isin(b[:, 0], a)]

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.