close

How to delete all columns in DataFrame except certain ones?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to delete all columns in DataFrame except certain ones 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 delete all columns in DataFrame except certain ones?

  1. How to delete all columns in DataFrame except certain ones?

    If you have more than two columns that you want to drop, let's say 20 or 30, you can use lists as well. Make sure that you also specify the axis value.

  2. delete all columns in DataFrame except certain ones

    If you have more than two columns that you want to drop, let's say 20 or 30, you can use lists as well. Make sure that you also specify the axis value.

Method 1

If you have more than two columns that you want to drop, let’s say 20 or 30, you can use lists as well. Make sure that you also specify the axis value.

drop_list = ["a","b"]
df = df.drop(df.columns.difference(drop_list), axis=1)

Method 2

In [48]: df.drop(df.columns.difference(['a','b']), 1, inplace=True)
Out[48]:
   a  b
0  1  2
1  4  3
2  8  9

or:

In [55]: df = df.loc[:, df.columns.intersection(['a','b'])]

In [56]: df
Out[56]:
   a  b
0  1  2
1  4  3
2  8  9
df = df[['a','b']]

or

df = df.loc[:, ['a','b']]

Summery

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