Best solution for selecting the columns that contain at least one True value in a pandas DataFrame

Viewed 631
In [4]: df = pd.DataFrame({'a': [True, False, True], 'b': [False, False, False], 
   ...: 'c': [False, False, False], 'd': [False, True, False], 
   ...: 'e': [False, False, False]})                                                                                                                                                                                                                                              


In [5]: df                                                                                                                                                                                                                                                                        
Out[5]: 
       a      b      c      d      e
0   True  False  False  False  False
1  False  False  False   True  False
2   True  False  False  False  False

In [6]: df[df.any()[df.any()].index]                                                                                                                                                                                                                                              
Out[6]: 
       a      d
0   True  False
1  False   True
2   True  False

The code under [6] does what I want. My question, however, is: is there a better solution? That is, more concise and/or more elegant.

1 Answers

One direct method is using df.loc with the mask generated by df.any() as input:

df.loc[:, df.any()]

       a      d
0   True  False
1  False   True
2   True  False

Another option is to index df.columns,

df[df.columns[df.any()]]

Or, df.keys():

df[df.keys()[df.any()]]
       a      d
0   True  False
1  False   True
2   True  False
Related