简体   繁体   中英

Making a list with the columns names that meet a condition

I have a dataframe with FALSE and TRUE in each cell... I want to make a list with the names of the columns that have at least one TRUE.

 col1 col2 col3 col4  
FALSE FALSE TRUE FALSE  
FALSE TRUE FALSE FALSE  
FALSE TRUE FALSE TRUE

I want this output:

[col2, col3, col4]

How can I do it?

This simple code does it:

colList = []
for col in df.columns:
    if True in df[col].unique():
        colList.append(col)

This gives you a colList with the names of the columns that have True in them. (Assuming your dataframe is named df )

You can do this to generate the list of columns:

cols=df.columns[(df == True).any()]

print(cols)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM