How to drop columns in a pandas dataframe

2

Pandas is a great tool for working on any machine learning or data science project. It’s a fundamental part of data wrangling. In this tutorial, we will show you how to drop a column in a pandas dataframe.

In order to drop a column in pandas, either select all the columns by using axis or select columns to drop with the drop method in the pandas dataframe.

The goals are to show both methods for dropping a column. The full code in Google Colabs is available to save or copy from directly since code can get kind of ugly in a web post.

The first way to drop columns in a pandas dataframe is by using axis.

For the following dataframe you will see there is a column called pclass.
pandas drop a column

In order to drop pclass add the following code where “titanic” is our dataframe.

See full code.

https://gist.github.com/craine/b9d4a986c8764f13201d45d034cf5f53

This code drops the column pclass. But what is that axis=1 you ask?
axis=1 is the column. If it were axis=0 it would be the row.

axis=1

There is another way to drop a column from a pandas dataframe, which is by using column instead of axis=1.

titanic drop sex

https://gist.github.com/craine/3459c1fa97ff09da32f99dc02f71378a

Full code example below:
https://gist.github.com/craine/73635c6606fd2a1be6ef95c4c643608d

Bonus. Go check out our code to see how to drop two columns at once in a pandas dataframe.

2 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here