ADVERTISEMENT
ADVERTISEMENT

Delete a column from a Pandas DataFrame

Given a DataFrame, we have to delete a column using del() method.
Submitted by Pranit Sharma, on April 03, 2022

In data analysis, deletion is an important primary operation. Deletion of a column can be performed using the del() method. In order to delete a column in a DataFrame, pandas has a method called del(). It allows us to remove columns according to the given column name.

Syntax:

del(df['column_name'])

Note: Python maps this method to an internal method of DataFrame (df.__delitem__('column name')) which is responsible for the deletion of the column.

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

import pandas as pd

Python code to delete a column from a Pandas DataFrame

Example 1:

# 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:

# 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 »



ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.