In the lesson, we learned how to add columns to a dataframe, but what if wanted to remove them?
In addition to being able to add columns, we have the ability to remove columns of a dataframe in Pandas.
There are a few ways you can go about removing columns from a dataframe:
Creating a new dataframe, and including just the columns you want to keep from the original dataframe. For example, if we only wanted to include these columns from a dataframe, it effectively “removes” all the other columns not included:
new_df = df[['col1', 'col4']]
You can utilize the built-in
drop()method, to delete a specific column. In order to drop a column, we must specify
axis=1. We can do so as follows:
df.drop('col3', axis=1, inplace=True)
To drop multiple columns at once, we can enter in multiple column names as a list using
drop(), like so:
df.drop(['col3', 'col5'], axis=1, inplace=True)