# How to drop a column in Python

In this article, lets discuss how to drop a column in Pandas Dataframe in Python.

For demonstrating this, first lets create a dummy dataframe.

import pandas as pd data = { 'A':['a1', 'a2', 'a3', 'a4', 'a5'], 'B':['b1', 'b2', 'b3', 'b4', 'b5'], 'C':['c1', 'c2', 'c3', 'c4', 'c5'], 'D':['d1', 'd2', 'd3', 'd4', 'd5'], 'E':['e1', 'e2', 'e3', 'e4', 'e5'] } df = pd.DataFrame(data) df

Output:

A B C D E 0 a1 b1 c1 d1 e1 1 a2 b2 c2 d2 e2 2 a3 b3 c3 d3 e3 3 a4 b4 c4 d4 e4 4 a5 b5 c5 d5 e5

So now we’ve got the dataframe. Now let’s use drop() method to drop a column from the dataframe. By using this method, we can drop a specific single column.

import pandas as pd data = { 'A':['a1', 'a2', 'a3', 'a4', 'a5'], 'B':['b1', 'b2', 'b3', 'b4', 'b5'], 'C':['c1', 'c2', 'c3', 'c4', 'c5'], 'D':['d1', 'd2', 'd3', 'd4', 'd5'], 'E':['e1', 'e2', 'e3', 'e4', 'e5'] } df = pd.DataFrame(data) #remove column name 'A' print(df.drop(['A'], axis = 1))

Output:

B C D E 0 b1 c1 d1 e1 1 b2 c2 d2 e2 2 b3 c3 d3 e3 3 b4 c4 d4 e4 4 b5 c5 d5 e5

Remove column based on column index:

import pandas as pd data = { 'A':['a1', 'a2', 'a3', 'a4', 'a5'], 'B':['b1', 'b2', 'b3', 'b4', 'b5'], 'C':['c1', 'c2', 'c3', 'c4', 'c5'], 'D':['d1', 'd2', 'd3', 'd4', 'd5'], 'E':['e1', 'e2', 'e3', 'e4', 'e5'] } df = pd.DataFrame(data) #removing column index 1, you can remove multiple column indices at a time df.drop(df.columns[[1]], axis = 1, inplace = True) df

Output:

A C D E 0 a1 c1 d1 e1 1 a2 c2 d2 e2 2 a3 c3 d3 e3 3 a4 c4 d4 e4 4 a5 c5 d5 e5

Subscribe

Login

Please login to comment

0 Discussion