Find Pandas dataframe column based on values, in Python
Question: I have 2 Pandas Dataframes in Python. Here they are:

    
    
    import numpy as np
    import pandas as pd
    df = pd.DataFrame(np.random.rand(10,3),columns=list('ABC'))
    df2 = pd.DataFrame(np.random.rand(10,3),columns=list('ABC'))
    df['A'] = 1
    print df
    print df2
    
       A         B         C
    0  1  0.333141  0.803991
    1  1  0.043958  0.582038
    2  1  0.833433  0.782856
    3  1  0.722592  0.237912
    4  1  0.634979  0.664208
    5  1  0.809748  0.889524
    6  1  0.110342  0.650617
    7  1  0.035417  0.251089
    8  1  0.481492  0.128792
    9  1  0.190135  0.213608
    
              A         B         C
    0  0.897373  0.599721  0.361668
    1  0.495024  0.471351  0.090395
    2  0.651174  0.621328  0.721208
    3  0.253459  0.567619  0.104370
    4  0.357627  0.616717  0.775327
    5  0.164323  0.716166  0.740565
    6  0.841509  0.464837  0.398952
    7  0.398680  0.186555  0.293076
    8  0.298785  0.784237  0.704184
    9  0.124763  0.384852  0.307361
    

As you can see in `df`, there is one column with **only** 1's.

I need to do the following:

  1. Find the name of the column in a Dataframe (`df`) that contains **only** 1's in all rows.
  2. Drop that column from `df`
  3. Drop that **SAME** column from `df2`

I would like to get this:

    
    
              B         C
    0  0.333141  0.803991
    1  0.043958  0.582038
    2  0.833433  0.782856
    3  0.722592  0.237912
    4  0.634979  0.664208
    5  0.809748  0.889524
    6  0.110342  0.650617
    7  0.035417  0.251089
    8  0.481492  0.128792
    9  0.190135  0.213608
    
              B         C
    0  0.599721  0.361668
    1  0.471351  0.090395
    2  0.621328  0.721208
    3  0.567619  0.104370
    4  0.616717  0.775327
    5  0.716166  0.740565
    6  0.464837  0.398952
    7  0.186555  0.293076
    8  0.784237  0.704184
    9  0.384852  0.307361
    

Is there a way to do this?


Answer: You can use `DataFrame.apply` with `axis=0` to apply a function to every
column of a dataframe. In your case you want to check whether `all(col==1)`
for each column. Then you can pick out the columns using a list comprehension,
and finally use `DataFrame.drop` do drop the columns:

    
    
    allonecols = df.apply(lambda col: all(col==1), axis = 0)
    allonecols 
    A     True
    B    False
    C    False
    dtype: bool
    
    dropcols = [k for k,v in allonecols.to_dict().items() if v]  
    dropcols 
    ['A']
    
    df2.drop(dropcols, axis = 1)
    

