What is the DataFrame.pop() method in Pandas?
Syntax
# SignatureDataFrame.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
If the column with the specified name does not exist, it raisesKeyError.
Example
main.py
data.csv
import pandas as pd# including pandas packagedf= pd.read_csv("data.csv")# popping Medical Expenses# from above loaded datasetpopped_column = df.pop("Medical Expenses")# printing on screenprint(popped_column)
Explanation
-
Line 3: We use
read_csvfrom Pandas package to load thedata.csvdataset. -
Line 6: We invoke
DataFrame.pop("Medical Expenses")to get theMedical Expensescolumn fromdata.csvfile. It returns column values as Pandas series. -
Line 8: We print the removed column stored in the
popped_columnvariable as Pandas series.