Felix
Felix

Reputation: 2668

Filter 2D-array rows by a 1D-array

I have a result of a database query as an nd-array. I'd like to filter the result by a list of IDs in the first column of the result.

Query result:    Filter:     Desired outcome:
ID | Field       ID          ID | Field
---+------       ---         ---+------
0  | Asd         1           1  | Wat
1  | Wat         2           2  | Cat
2  | Cat
6  | Yep

Of course list comprehensions could be used:

out = [i for i in result if i[0] in filter]

but I'm looking for a NumPy-type solution, like np.where. And this method returns a list of NumPy arrays, not an ndarray. So, completely unusable.

Do you know of such method?

Edit: sandbox for experimentation

Here's code to copy-paste if you'd like to try.

a = np.array([[0, 'asd'],[1, 'wat'],[2, 'cat'],[6, 'yep']])
b = np.array([1, 2], dtype=str)

out = np.array([i for i in a if i[0] in b])
> array([['1', 'wat'], ['2', 'cat']])

Upvotes: 1

Views: 1030

Answers (1)

Antonina
Antonina

Reputation: 604

Do you like to get such result?

>>> c = a[np.where(np.in1d(a[:, 0], b))]
>>> c
array([['1', 'wat'],
       ['2', 'cat']],
      dtype='<U11')
>>> type(c)
<class 'numpy.ndarray'>

Upvotes: 2

Related Questions