Open In App

How to Delete a column from Pandas DataFrame

Improve
Improve
Like Article
Like
Save
Share
Report

Deleting data is one of the primary operations when it comes to data analysis. Very often we see that a particular column in the DataFrame is not at all useful for us and having it may lead to problems so we have to delete that column.

For example, if we want to analyze the students’ BMI of a particular school, then there is no need to have the religion column/attribute for the students, so we prefer to delete the column.

Deleting a Column from DataFrame

You can remove column from a DataFrame using del Keyword.

Let us now see the syntax to use del Keyword:

Syntax:

del df['column_name']

Examples:

Let’s understand how to use the del keyword and delete columns from DataFrame in Python:

Example 1:  

Python3




# importing the module
import pandas as pd
  
# creating a DataFrame
my_df = {'Name': ['Rutuja', 'Anuja'], 
         'ID': [1, 2], 'Age': [20, 19]}
df = pd.DataFrame(my_df)
display("Original DataFrame")
display(df)
  
# deleting a column
del df['Age']
  
display("DataFrame after deletion")
display(df)


Output :  

Original DataFrame and DataFrame after deletionAs you can see, the column ‘Age’ has been dropped.

Example 2:  

Python3




# importing the module
import pandas as pd
  
# creating a DataFrame
my_df = {'Students': ['A', 'B', 'C', 'D'], 
         'BMI': [22.7, 18.0, 21.4, 24.1], 
         'Religion': ['Hindu', 'Islam'
                      'Christian', 'Sikh']}
df = pd.DataFrame(my_df)
display("Original DataFrame")
display(df)
  
# deleting a column
del df['Religion']
  
display("DataFrame after deletion")
display(df)


Output :  

DataFrame before and after column deletion

Note that the unnecessary column, ‘Religion’ has been deleted successfully.

Also Read: How to drop one or multiple columns in Pandas Dataframe

Conclusion

Deleting unnecessary columns is a very crucial step to clean data in data analysis. Not all attributes(columns) are useful to generate insights, so it’s better to delete those columns from the DataFrame.

Deleting a column in Pandas DataFrame is very easy. In this tutorial, we have shown how to delete a column/attribute from a Pandas DataFrame using del keyword.



Last Updated : 05 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads