kiril
kiril

Reputation: 5212

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:

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)

Upvotes: 0

Views: 46

Answers (1)

Marco_CH
Marco_CH

Reputation: 3294

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

Upvotes: 1

Related Questions