How to delete a column from a Pandas DataFrame?

Deleting column from DataFrame: In this tutorial, we will learn how can we delete / drop a column from a Pandas DataFrame in Python? By Pranit Sharma Last updated : April 10, 2023

Delete a column from a Pandas DataFrame

To delete a column from a Pandas DataFrame, we use del() method. This method allows us to remove columns according to the given column name. Python maps this method to an internal method of DataFrame (df.__delitem__('column name')) which is responsible for the deletion of the column.

Syntax

del df["column_name"]
# or
del(df['column_name'])

Note: To work with Python Pandas, we need to import the pandas library. Below is the syntax,

import pandas as pd

Example 1: Delete a column from a Pandas DataFrame

# Importing pandas package
import pandas as pd

# Create a dictionary
d = {
    "Brands": ['Ford','Toyota','Renault'],
    "Cars":['Ecosport','Fortunar','Duster'],
    "Price":[900000,4000000,1400000]
}

# Creating a dataframe
df = pd.DataFrame(d,index=[1,2,3])

# Printing original DataFrame
print("The original DataFrame:")
print(df,"\n")

# Deleting the column "Price"
del df["Price"]

# Printing the updated DataFrame
print("DataFrame after deletion:")
print(df)

Output

The original DataFrame:
    Brands  ...    Price
1     Ford  ...   900000
2   Toyota  ...  4000000
3  Renault  ...  1400000

[3 rows x 3 columns] 

DataFrame after deletion:
    Brands      Cars
1     Ford  Ecosport
2   Toyota  Fortunar
3  Renault    Duster

Example 2: Delete a column from a Pandas DataFrame

# Importing pandas package 
import pandas as pd 
   
# Dictionary having students data
students = {
    'Name':['Alvin', 'Alex', 'Peter'],
    'Age':[21, 22, 19]
} 
   
# Convert the dictionary into DataFrame  
dataframe = pd.DataFrame(students) 

# Print the data before deleting column
print("Data before deleting column...")
print(dataframe)
print()

# Deleting the column "Age"
del(dataframe['Age'])

# Print the data after deleting column
print("Data after deleting column...")
print(dataframe)
print()

Output

Data before deleting column...
    Name  Age
0  Alvin   21
1   Alex   22
2  Peter   19

Data after deleting column...
    Name
0  Alvin
1   Alex
2  Peter

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.