Question
Asked By – Alexis Eggermont
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?
Now we will see solution for issue: Drop columns whose name contains a specific string from pandas DataFrame
Answer
import pandas as pd
import numpy as np
array=np.random.random((2,4))
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']
df=df[cols]
print df
toto riri
0 0.572528 0.144891
1 0.332540 0.741412
This question is answered By – Nic
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0