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

Viewed 107

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]

2 Answers

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]
Related