Home > Back-end >  df loc to deselect columns
df loc to deselect columns

Time:10-02

I'm trying to deselect columns using df.loc. I want to select all columns that does not have names that includes e.g. "X".

I can filter the columns with:

df.filter(like='X')

, but how can I exclude them?

CodePudding user response:

You could use the following code:

import pandas as pd
import numpy as np

array=np.random.random((2,3))
df=pd.DataFrame(array, columns=('X', 'Y', 'Z'))

          X         Y         Z
0  0.101461  0.459929  0.987757
1  0.027182  0.937235  0.045712

df.loc[:,~df.columns.str.contains('X', case=False)] 

Output:

          Y         Z
0  0.459929  0.987757
1  0.937235  0.045712

CodePudding user response:

You can use pandas.Index.difference :

df[df.columns.difference(df.filter(like='X').columns, sort=False)]
  • Related