How to drop the last column of a Pandas DataFrame?

Remove last column from pandas DataFrame

In a nutshell, you are able to drop the last column of your DataFrame using one of the following techniques:

By column index:

your_df.drop (columns = your_df.columns[-1], inplace= True)

or alternatively by column name:

your_df = your_df.drop('last_column_name')

Create example data

First, we will import pandas and create some data that you can use to follow along:

import pandas as pd

language = ['Go', 'Java', 'R', 'Python', 'Python']
signups = [120, 151, 186, 107, 156]
attendees = [80,22,134, 45, 76]
campaign = pd.DataFrame(dict (language = language, signups = signups, attendees = attendees))

campaign.head()

Let’s look at the data:

languagesignupsattendees
0Go12080
1Java15122
2R186134
3Python10745
4Python15676

We can look into the column index:

campaign.columns

This return the following Index object:

Index(['language', 'signups', 'attendees'], dtype='object')

Remove the last column in pandas

Now that we have a DataFrame, we can slice the column index, in the same fashion that you would have done with a simple Python list.

The last column index is -1, hence we can write the following code to drop that column from our DF:

campaign.drop (columns = campaign.columns[-1], inplace=True)

This returns the following DataFrame:

languagesignups
0Go120
1Java151
2R186
3Python107
4Python156

Delete the last column by label (name)

We can accomplish a similar result by passing the last column name to the drop method:

campaign.drop(columns = 'attendees', inplace=True)

Drop the two last columns using iloc

We can also subset our DataFrame columns using the iloc indexer. Let’s take for example a case in which we want to save all columns but the last two into a new DataFrame. Using standard Python sequence slicing:

campaign_2 = campaign.iloc[:,:-2]

Remove only first and last columns

Last case for today, is to select all columns except the first and the last. In this case we’ll pass a list of indexes to drop. Index 0 is the first column, index -1 is the last one.

campaign.drop (columns = campaign.columns[[0,-1]])

Additional Learning

How to divide values in pandas columns by other cell values?