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
  • 646
  • 8
  • 27

2 Answers2

2

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
halfer
  • 19,824
  • 17
  • 99
  • 186
BENY
  • 317,841
  • 20
  • 164
  • 234
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
  • 565
  • 4
  • 8