1

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']])
2
  • You forgot to give result in your example. Commented Jul 20, 2018 at 7:16
  • @Kefeng91 Oops, the array names are now fixed. Commented Jul 20, 2018 at 7:31

1 Answer 1

2

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'>
Sign up to request clarification or add additional context in comments.

1 Comment

That's perfect, thanks! I knew there was such a function.

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.