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.
In order to drop pclass add the following code where “titanic” is our dataframe.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
titanic.drop(['pclass'], axis=1) |
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.
There is another way to drop a column from a pandas dataframe, which is by using column instead of axis=1.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
titanic.drop(columns=['sex']) |
Full code example below:
Bonus. Go check out our code to see how to drop two columns at once in a pandas dataframe.
[…] previous tutorial showed you how to drop columns in a pandas dataframe. Now we will look at how to drop rows in a pandas […]
[…] allow for many methods for adding and dropping content. We have covered how to drop a column and how to drop a row in pandas dataframe. What if you want to add a column to pandas? You can […]