To drop the last column from a DataFrame using Pandas in Python, you can use the iloc[]
method to select all rows and all columns except the last one. You can drop the last column from the pandas DataFrame using either iloc[],
drop(),
pop()
functions and del
keyword. In this article, I will explain how to drop/delete/remove the last column from Pandas DataFrame with examples.
drop()
function is used to drop columns or drop rows from DataFrame;- Use
axis
param to specify what axis you would like to delete. By defaultaxis=0
meaning to delete rows. Useaxis=1
or columns param to delete columns. - Use
inplace=True
to delete row/column in place meaning on existing DataFrame without creating copy.
Related: In Pandas, you can drop the first/last n columns from DataFrame.
1. Quick Examples of Drop Last Column From DataFrame
If you are in a hurry, below are some quick examples of how to drop/delete the last column from DataFrame.
# Quick examples of drop last column from dataframe
# Example 1: Drop last column of dataframe
# Using iloc[]
df2 = df.iloc[: , :-1]
# Example 2: By using iloc[]
# To select all columns
# Except the last column
df2 = df[df.columns[:-1]]
# Example 3: Drop last column of dataframe using drop()
df.drop(columns=df.columns[-1], axis=1, inplace=True)
# Example 4: Using drop() function to delete last column
df.drop(df.columns[len(df.columns)-1], axis=1, inplace=True)
# Example 5: Using DataFrame.drop() function
# To drop last column
df2 = df.drop(df.columns[-1],axis=1)
# Example 6: Drop last column of dataframe
# Using pop()
df.pop(df.columns[-1])
# Example 7: Use del keywords
del df[df.columns[-1]]
Now, Let’s create Pandas DataFrame using data from a Python dictionary, where the columns are Courses
, Fee
, Duration
and Discount
.
# Create DataFrame
import pandas as pd
import numpy as np
technologies= ({
'Courses':["Spark","PySpark","Hadoop","Pandas"],
'Fee': [22000,25000,30000,35000],
'Duration':['30days','50days','40days','35days'],
'Discount':[1000,2000,2500,1500]
})
index_labels=['r1','r2','r3','r4']
df = pd.DataFrame(technologies,index=index_labels)
print("Create DataFrame:\n",df)
Yields below output.
2. Pandas Drop Last Column using iloc[]
Using DataFrame.iloc[] with -1 as index you can drop the last column from Pandas DataFrame. For example use, df.iloc[:,:-1]
to select all columns except the last one and then assign it back to the original variable which ideally drops the last column from DataFrame.
In the iloc[:, :-1]
part, :
selects all rows, and :-1
selects all columns up to (but not including) the last one. This effectively drops the last column from the DataFrame.
# Drop last column of dataframe
# Using iloc[]
df2 = df.iloc[:, :-1]
print("Dropping last column:\n", df2)
# By using iloc[] to select all columns
# Except the last column
df2 = df[df.columns[:-1]]
print("Dropping last column:\n", df2)
Yields below output.
Related: In Pandas, you can also drop the first column from DataFrame.
3. Drop Last Column of DataFrame Using drop()
Alternatively, you can also use DataFrame.drop() function to delete the last column. Use axis=1
to specify the columns and inplace=True
to apply the change on the existing DataFrame.
In the below example, df.columns[-1]
gets the label of the last column, and axis=1
specifies that we want to drop a column. The resulting DataFrame (df
) will have the last column removed. df.columns[-1]
returns Duration
which is the last column from our DataFrame.
# Using DataFrame.drop() function
# To drop last column
df2 = df.drop(df.columns[-1],axis=1)
print("Dropping last column:\n", df)
# Drop last column of dataframe using drop()
df.drop(columns=df.columns[-1], axis=1, inplace=True)
print("Dropping last column:\n", df)
# Using drop() function to delete last column
df.drop(df.columns[len(df.columns)-1], axis=1, inplace=True)
print("Dropping last column:\n", df)
Yields the same output as above.
4. Drop Last Column using pop()
Similarly, you can use DataFrame.pop()
function to drop the last column of pandas DataFrame and also returned the deleted column as a series. So, you can select the last column of DataFrame by using df.columns[-1]
, it will select all columns except the last column of DataFrame.
In this example, df.columns[-1]
gets the label of the last column, and df.pop()
removes and returns that column. The resulting DataFrame (df
) will no longer contain the last column.
# Drop last column of dataframe
# Using pop()
df.pop(df.columns[-1])
print("Dropping last column:\n", df)
Yields the same output as above.
5. Use del Keyword to Drop Last Column of Pandas DataFrame
You can use the del
keyword to remove the last column from a Pandas DataFrame. For instance, df.columns[-1]
gets the label of the last column, and del df[df.columns[-1]]
removes that column from the DataFrame. The resulting DataFrame (df
) will no longer contain the last column. Note that this modifies the original DataFrame in place.
# Use del keywords
del df[df.columns[-1]]
print(df)
6. Complete Example For Drop Last Column From DataFrame
import pandas as pd
import numpy as np
technologies= ({
'Courses':["Spark","PySpark","Hadoop","Pandas"],
'Fee': [22000,25000,30000,35000],
'Duration':['30days','50days','40days','35days'],
'Discount':[1000,2000,2500,1500]
})
index_labels=['r1','r2','r3','r4']
df = pd.DataFrame(technologies,index=index_labels)
print(df)
# Drop last column of dataframe using iloc[]
df2 = df.iloc[: , :-1]
print(df2)
# By using iloc[] to select all columns
# Except the last column
df2 = df[df.columns[:-1]]
print(df2)
# Drop last column of dataframe using drop()
df.drop(columns=df.columns[-1], axis=1, inplace=True)
print(df)
# Using drop() function to delete last column
df.drop(df.columns[len(df.columns)-1], axis=1, inplace=True)
print(df)
# Using DataFrame.drop() function to drop last column
df2 = df.drop(df.columns[-1],axis=1)
print(df2)
# Drop last column of dataframe using pop()
df.pop(df.columns[-1])
print(df)
# Use del keywords
del df[df.columns[-1]]
print(df)
Frequently Asked Questions on Drop Last Column From DataFrame
You can drop the last column from a Pandas DataFrame using various methods, such as iloc[]
, drop()
, pop()
, or the del
keyword.
Dropping the last column using any of the mentioned methods modifies the original DataFrame in place. If you want to keep the original DataFrame unchanged, you can assign the result to a new variable.
Performance differences are generally negligible for small to medium-sized DataFrames. However, for very large DataFrames, there might be slight variations. It’s recommended to choose the method that fits your specific use case and coding style.
You can drop columns based on column names instead of positions using the drop()
method in Pandas. For example, the columns_to_drop
list contains the names of the columns you want to remove. The drop()
method is then used with the columns
parameter to drop the specified columns. The resulting DataFrame (df
) will not contain the columns specified in the columns_to_drop
list.
You can drop multiple columns at once using any of the mentioned methods. For example, using iloc[]
If you want to drop columns from a DataFrame without modifying the original DataFrame, you should create a new DataFrame with the desired subset of columns. The original DataFrame remains unchanged.
Conclusion
In this article, I have explained how to drop the last column from Pandas DataFrame using DataFrame.iloc[]
, DataFrame.drop()
, and DataFrame.pop()
, and del
Keyword functions with examples.
Happy Learning !!
Related Articles
- Pandas Drop Rows by Index
- Drop multiple columns by index
- How to drop the Pandas column by index?
- Drop Pandas first column from DataFrame.
- Get First N Rows of Pandas DataFrame
- Pandas Drop First N Rows From DataFrame
- Pandas Drop Last N Rows From DataFrame
- Pandas Delete Last Row From DataFrame
- How to drop Pandas Columns from DataFrame?
- Pandas Drop Multiple Columns From DataFrame
- How to Drop Duplicate Columns in Pandas DataFrame?
- Pandas Drop First/Last N Columns From DataFrame
- Pandas Drop Columns with NaN or None Values