Search code examples
pandasmultiple-columns

Select columns from data frame using 1, 0 list , pandas


I have a list of 1,0 where each element is corresponding to an index of a column on a data frame, for example: df.columns = ['a','b','c'] binary_list = [0,1,0]

based on that I want to select only b column from the data frame as on my binary list it has 1 only corresponds to b

is there a way to perform that in pandas?

P.S this is my first time posting on stackoverflow, apologies if I am not following a specific styling


Solution

  • If the binary list is aligned with the columns, you can use boolean indexing:

    df = pd.DataFrame([[1, 2, 3]], columns=['a', 'b', 'c'])
    
    binary_list = [0,1,0]
    
    df.loc[:, map(bool, binary_list)]
    

    Output:

       b
    0  2