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

How to check if a pandas column has anything other than specified values?

Say I have a pandas dataframe, with column A, and we want all the values in that column to be of type category with either L or R as the value.

How can I raise an exception if we detect that this column has any value other than L or R? That includes if it was None/null/NaN

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

>Solution :

We can filter on L and R and then we get the opposite of that filter using the ~ operator like so :

>>> df[~(df['A'].isin(['L', 'R']))]

To get a boolean saying that some additionnal values are present in the DataFrame, we can write :

>>> len(df[~(df['A'].isin(['L', 'R']))]) == 0
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