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.
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.
There is another way to drop a column from a pandas dataframe, which is by using column instead of axis=1.
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.
[…] 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 […]