How to select all columns, except one column in pandas? How to select all columns, except one column in pandas? python python

How to select all columns, except one column in pandas?


When the columns are not a MultiIndex, df.columns is just an array of column names so you can do:

df.loc[:, df.columns != 'b']          a         c         d0  0.561196  0.013768  0.7728271  0.882641  0.615396  0.0753812  0.368824  0.651378  0.3972033  0.788730  0.568099  0.869127


Don't use ix. It's deprecated. The most readable and idiomatic way of doing this is df.drop():

>>> df          a         b         c         d0  0.175127  0.191051  0.382122  0.8692421  0.414376  0.300502  0.554819  0.4975242  0.142878  0.406830  0.314240  0.0931323  0.337368  0.851783  0.933441  0.949598>>> df.drop('b', axis=1)          a         c         d0  0.175127  0.382122  0.8692421  0.414376  0.554819  0.4975242  0.142878  0.314240  0.0931323  0.337368  0.933441  0.949598

Note that by default, .drop() does not operate inplace; despite the ominous name, df is unharmed by this process. If you want to permanently remove b from df, do df.drop('b', inplace=True).

df.drop() also accepts a list of labels, e.g. df.drop(['a', 'b'], axis=1) will drop column a and b.


df[df.columns.difference(['b'])]Out:           a         c         d0  0.427809  0.459807  0.3338691  0.678031  0.668346  0.6459512  0.996573  0.673730  0.3149113  0.786942  0.719665  0.330833


matomo