简体   繁体   中英

Obtain the pandas dataframe column names in a list when one cell value equals to a specific string

I have a pandas dataframe with around 20-30 columns. I would like to obtain the column names in a list when one cell value equals to the string "Fail".

The dataframe would look like this:

    Column_1 Column_2 ... Column_30
0      Pass   Pass          Fail
1      Pass   Pass          Pass
2      Fail   Pass          Pass
3      Pass   Pass          Pass
4      Pass   Pass          Pass
..

The expected result looks like such [Column_1, Column 30]

I think this should do the trick

df.columns[(df=='Fail').any(axis=0)]

This gives you the columns names for each column that contains at least one 'Fail' in its rows as a pandas.Index. If it must be a list, just add .tolist() at the end.

You can do a list comprehension that incorporates a value check:

[col for col in df.columns if 'Fail' in df[col].values]

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