Q:

Delete a column from a Pandas DataFrame

belongs to collection: Python Pandas Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Pandas Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to rename columns in Pandas DataFrame?... >>
<< Python Pandas | Adding new column to existing Data...