Alexis Eggermont Alexis Eggermont - 4 months ago 75x
Python Question

Pandas dataframe: drop columns whose name contains a specific string

I have a pandas dataframe with the following column names:

Result1, Test1, Result2, Test2, Result3, Test3, etc...

I want to drop all the columns whose name contains the word "Test". The numbers of such columns is not static but depends on a previous function.

How can I do that?

Nic Nic
import pandas as pd

import numpy as np


df=pd.DataFrame(array, columns=('Test1', 'toto', 'test2', 'riri'))

print df

      Test1      toto     test2      riri
0  0.923249  0.572528  0.845464  0.144891
1  0.020438  0.332540  0.144455  0.741412

cols = [c for c in df.columns if c.lower()[:4] != 'test']


print df
       toto      riri
0  0.572528  0.144891
1  0.332540  0.741412