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 column of lists in pandas dataframe

So I want to filter a column of lists which should only contain specific items.

This my original table:

id code
1 [Hes3086, Hes3440, Hes3220]
2 [Hes3440, Nee8900]
3 [Hes1337, Hes3440]
4 [Nee8900, Hes3440]
5 [Hes1337, Nee8900]
6 [Hes3220, Nee8900]
7 [Hes3220, Nee8900, Hes3440]

I want the rows which only have specific items in the lists: Hes3440, Nee8900, Hes3220

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

Which should generate the following output:

id code
2 [Hes3440, Nee8900]
4 [Nee8900, Hes3440]
6 [Hes3220, Nee8900]
7 [Hes3220, Nee8900, Hes3440]

I am able to filter the dataset by making sure that at least one of the desired items is in each row, but this is not what I want.

Would appreciate any help!

thanks,
M

>Solution :

Use issubset in boolean indexing with Series.map:

L = ['Hes3440','Nee8900','Hes3220']

df = df[df.code.map(lambda x: set(x).issubset(L))]
print (df)
   id                         code
1   2           [Hes3440, Nee8900]
3   4           [Nee8900, Hes3440]
5   6           [Hes3220, Nee8900]
6   7  [Hes3220, Nee8900, Hes3440]

List comprehension alternative:

df = df[[set(x).issubset(L) for x in df.code]]
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