Get column name where value is something in pandas dataframe

Just wanted to add that for a situation where multiple columns may have the value and you want all the column names in a list, you can do the following (e.g. get all column names with a value=”x”):

df.apply(lambda row: row[row == 'x'].index, axis=1)

The idea is that you turn each row into a series (by adding axis=1) where the column names are now turned into the index of the series. You then filter your series with a condition (e.g. row == 'x'), then take the index values (aka column names!).

Leave a Comment