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

What is the best approach to remove in pandas all columns with all values equals to False?

I’ve seen in this question how to drop columns with all nan, but I’m looking for a way to remove all columns with all False values.

Using the info in that question, I’m thinking of replacing False with nan, dropping them, and then replacing nan back with False, but I don’t know if that is the best approach.

A working piece of code with my approach would be as follows:

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

df = pd.DataFrame(data={'A':[True, True, False], 'B': [False, True, False], 'C':[False, False, False], 'D': [True, True, True]})

df.replace(to_replace=False, value=np.nan, inplace=True)
df.dropna(axis=1, how='all', inplace=True)
df.fillna(False, inplace=True)

>Solution :

You could use:

df.loc[:,~df.eq(False).all()]

Output:

    A       B       D
0   True    False   True
1   True    True    True
2   False   False   True
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