4

col_exclusions = ['numerator','Numerator' 'Denominator', "denominator"]

dataframe

id prim_numerator sec_Numerator tern_Numerator tern_Denominator final_denominator Result

1       12                23           45          54                      56         Fail

Final output is id and Result

4
  • 1
    Does this answer your question? Delete column from pandas DataFrame Commented Feb 18, 2020 at 9:58
  • possible duplicate: stackoverflow.com/questions/51167612/… Commented Feb 18, 2020 at 9:58
  • @AkshayNevrekar This is not my question Commented Feb 18, 2020 at 10:02
  • Im having column names combined with word numerator etc so if numerator comes in any place means i have to remove that Commented Feb 18, 2020 at 10:03

3 Answers 3

5

using regex

import re

pat = re.compile('|'.join(col_exclusions),flags=re.IGNORECASE)

final_cols = [c for c in df.columns if not re.search(pat,c)]

#out:

['id', 'Result']

print(df[final_cols])

   id Result
0   1   Fail

if you want to drop

df = df.drop([c for c in df.columns if re.search(pat,c)],axis=1)

or the pure pandas approach thanks to @Anky_91

df.loc[:,~df.columns.str.contains('|'.join(col_exclusions),case=False)]
Sign up to request clarification or add additional context in comments.

Comments

0

You can be explicit and use del for columns that contain the suffixes in your input list:

for column in df.columns:
    if any([column.endswith(suffix) for suffix in col_exclusions]):
        del df[column]

Comments

0

You can also use the following approach where the column names are splitted then matched with col_exclusions

df.drop(columns=[i for i in df.columns if i.split("_")[-1] in col_exclusions], inplace=True)
print(df.head())

1 Comment

classic case of FGITW, smh :-(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.