What is the DataFrame.pop() method in Pandas?

Overview

In Pandas, the DataFrame.pop(column_name) method is used to remove the specified column from a DataFrame.

Note: This method is common in numerous data structures and does not take any argument value.

Syntax

# Signature
DataFrame.pop(column_name)

Parameter

It takes a single parameter, column_name, which represents the name of the column to be removed from the DataFrame.

Return value

It returns the removed column as a Pandas seriesone dimensional label arrays object.

If the column with the specified name does not exist, it raises KeyError.

Example

main.py
data.csv
import pandas as pd
# including pandas package
df= pd.read_csv("data.csv")
# popping Medical Expenses
# from above loaded dataset
popped_column = df.pop("Medical Expenses")
# printing on screen
print(popped_column)

Explanation

  • Line 3: We use read_csv from Pandas package to load the data.csv dataset.

  • Line 6: We invoke DataFrame.pop("Medical Expenses") to get the Medical Expenses column from data.csv file. It returns column values as Pandas series.

  • Line 8: We print the removed column stored in the popped_column variable as Pandas series.

Note: The file data.csv contains all the employee data, including name, designation, medical allowance, bonus, and total as features.