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

Sociopath
  • 12,395
  • 17
  • 43
  • 69
rakesh
  • 123
  • 8
  • 1
    Does this answer your question? [Delete column from pandas DataFrame](https://stackoverflow.com/questions/13411544/delete-column-from-pandas-dataframe) – Sociopath Feb 18 '20 at 09:58
  • possible duplicate: https://stackoverflow.com/questions/51167612/what-is-the-best-way-to-remove-columns-in-pandas – 404pio Feb 18 '20 at 09:58
  • @AkshayNevrekar This is not my question – rakesh Feb 18 '20 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 – rakesh Feb 18 '20 at 10:03

3 Answers3

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)]
Umar.H
  • 20,495
  • 6
  • 30
  • 59
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]
arnaud
  • 2,950
  • 1
  • 8
  • 24
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())
Abhishek S
  • 879
  • 9
  • 22