Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter a list based on another list with multiple choices of elements

Suppose I have a list a=[1, 3, 4, 5, 7] and another list b=[0,0,1,1,3].

Now I want to filter a to make a new list where the corresponding position in b is 0 or 3. If I only want b to be 0, it’s simply a = a[b==0], but now it’s filtering based on a subset.
What I did is :

subset = [0, 1]
a = a[b in subset]

which is not correct and the error goes:ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I wonder what is the correct way to do so. Thanks!

>Solution :

If I understand your question right then you’re looking for np.isin:

a = np.array([1, 3, 4, 5, 7])
b = np.array([0, 0, 1, 1, 3])

print(a[np.isin(b, [0, 3])])

Prints:

[1 3 7]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading