close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to select all columns, except one column in pandas in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

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

  1. 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']

  2. 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']

Method 1

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         d
0  0.561196  0.013768  0.772827
1  0.882641  0.615396  0.075381
2  0.368824  0.651378  0.397203
3  0.788730  0.568099  0.869127

Method 2

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

>>> df

          a         b         c         d
0  0.175127  0.191051  0.382122  0.869242
1  0.414376  0.300502  0.554819  0.497524
2  0.142878  0.406830  0.314240  0.093132
3  0.337368  0.851783  0.933441  0.949598

>>> df.drop('b', axis=1)

          a         c         d
0  0.175127  0.382122  0.869242
1  0.414376  0.554819  0.497524
2  0.142878  0.314240  0.093132
3  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.

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read