Select everything except the list of columns from pandas dataframe

Is it possible to select the negation of this list from pandas dataframe ?. For example, let's say I have the following data file

T1_V2 T1_V3 T1_V4 T1_V5 T1_V6 T1_V7 T1_V8 1 15 3 2 NBN 4 16 14 5 HBN 1 10 10 5 NKN 

and I want to display all columns, but column T1_V6. I usually do this:

 df = df[["T1_V2","T1_V3","T1_V4","T1_V5","T1_V7","T1_V8"]] 

My question is, is there a way around this for the opposite, something like this

 df = df[!["T1_V6"]] 
+7
python pandas
source share
4 answers

If the column names are strings, you can do this as follows:

 df[df.columns - ["T1_V6"]] 

However, "set minus" does not work for numeric column names, so this is probably the preferred way to do this (also works with numeric column names):

 df[df.columns.difference(["T1_V6"])] 
+9
source share

For completeness, you can also easily use drop for this:

 df.drop(["T1_V6"], axis=1) 
+2
source share

I would suggest using DataFrame.drop ()

 columns_to _exclude = ['T1_V6'] old_dataframe = #Has all columns new_dataframe = old_data_frame.drop(columns_to_exclude, axis = 1) 

You can use inplace to make changes to the original data file itself.

 old_dataframe.drop(columns_to_exclude, axis = 1, inplace = True) #old_dataframe is changed 
+2
source share

You need to use List Comprehensions :

 [col for col in df.columns if col != 'T1_V6'] 
+1
source share

All Articles