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]]
CodePudding user response:
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]])
CodePudding user response:
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)]