How to Delete Column from Pandas DataFrame?

Pandas DataFrame.pop() – Delete Column

Pandas DataFrame.pop() function is used to delete a column from the DataFrame.

In this tutorial, we shall go through examples to learn how to use pop() to delete a column from Pandas DataFrame.

Example 1: Delete a column using pandas pop() function

In this example, we deleted a specific column, using column name, from the DataFrame with pop(). pandas pop() function updates the original dataframe. The data in the deleted column is lost.

Python Program

import pandas as pd

mydictionary = {'names': ['Somu', 'Kiku', 'Amol', 'Lini'],
	'physics': [68, 74, 77, 78],
	'chemistry': [84, 56, 73, 69],
	'algebra': [78, 88, 82, 87]}

#create dataframe
df_marks = pd.DataFrame(mydictionary)
print('Original DataFrame\n--------------')
print(df_marks)

#delete column
df_marks.pop('algebra')
print('\n\nDataFrame after deleting column\n--------------')
print(df_marks)
Run this program ONLINE

Output

pandas pop function example
pandas dataframe.pop()

Example 2: Delete a non-existing column using pandas pop() function

In this example, we will try deleting a column that is not present in the DataFrame.

When you try to delete a non-existing column of DataFrame using pop(), the function pop() throws KeyError.

Python Program

import pandas as pd

mydictionary = {'names': ['Somu', 'Kiku', 'Amol', 'Lini'],
	'physics': [68, 74, 77, 78],
	'chemistry': [84, 56, 73, 69],
	'algebra': [78, 88, 82, 87]}

#create dataframe
df_marks = pd.DataFrame(mydictionary)
print('Original DataFrame\n--------------')
print(df_marks)

#delete column that is not present
df_marks.pop('geometry')
print('\n\nDataFrame after deleting column\n--------------')
print(df_marks)
Run this program ONLINE

Output

pandas pop function throwing KeyError
pandas pop() throwing KeyError

Summary

In this tutorial of Python Examples, we learned how to delete a column from DataFrame using pop() with the help of well detailed example programs.