0

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

Community
  • 1
  • 1
newbie
  • 546
  • 7
  • 23

2 Answers2

2

IIUC we 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
BENY
  • 296,997
  • 19
  • 147
  • 204
0

Here's one way to do it.

# check each column for any matches from the items list.
matched = df.isin(items).any(axis=0)

# produce a list of column labels with a match.
matches = list(df.columns[matched])
cggarvey
  • 555
  • 4
  • 8