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

Selecting indices not in a subset from Pandas dataframe

I have a Python Pandas dataframe with many rows. The first column is "test_idx". For example:

df = 
test_idx sample value
1        1      1.2
1        2      -3.0
1        3      4.7
2        1      1.5
2        2      2.8

etc…

Assume I know that experiments invalid_tests = [2,3,7] are invalid. I would like to create a new Pandas dataframe cdf which contains only the valid tests.

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

There is a straight-forward way to do it, as I did it here:

valid_tests_idx = [] # indices of rows with valid tests
for i in range(len(df)):
    if not df["test_idx"].iloc[i] in invalid_tests:
        valid_tests_idx.append(i)
cdf = df.iloc[valid_tests_idx]

It works fine, but I ask if there is a more elegant way or an one-liner way to do it.

>Solution :

Use pandas tilde (~) operator for negation :

df[~df.test_idx.isin(invalid_tests)]
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