Search code examples
python-3.xpandasidentity-column

Get columns names if 'value' is in a list pandas Python


I need to find columns names if they contain one of these words COMPLETE, UPDATED and PARTIAL

This is my code, not working.

import pandas as pd

df=pd.DataFrame({'col1': ['', 'COMPLETE',''], 
             'col2': ['UPDATED', '',''],
             'col3': ['','PARTIAL','']},
            )
print(df)
items=["COMPLETE", "UPDATED", "PARTIAL"]
if x in items:
    print (df.columns)

this is the desired output:

enter image description here

I tried to get inspired by this question Get column name where value is something in pandas dataframe but I couldn't wrap my head around it


Solution

  • We can do isin and stack and where:

    s=df.where(df.isin(items)).stack().reset_index(level=0,drop=True).sort_index()
    s
    col1    COMPLETE
    col2     UPDATED
    col3     PARTIAL
    dtype: object