Python:Pandas .pop()
Published May 30, 2024
Contribute to Docs
In Pandas, the .pop() method removes a single specified column from a DataFrame object. In the process, the original DataFrame object gets modified and the removed column is returned as a Pandas Series object.
Syntax
pandas.DataFrame.pop(column_label)
DataFrame: Refers to the DataFrame object from which a column is removed.column_label: Represents the label of the column to be removed. This should be a string representing the column name.
Example
This example shows the .pop() method in use:
import pandas as pdd = {'col 1': [1, 2, 3, 4],'col 2': ['Red', 'Blue', 'Green', 'Pink'],'col 3': ['Oval', 'Circle', 'Square', 'Star'],'col 4': ['Sweet', 'Sour', 'Bitter', 'Salty']}df = pd.DataFrame(data = d)print(f"Original dataframe:\n{df}\n")data_pop = df.pop('col 3')print(f"Popped data:\n{data_pop}\n")print(f"DataFrame after pop:\n{df}\n")
The output is shown below:
Original dataframe:col 1 col 2 col 3 col 40 1 Red Oval Sweet1 2 Blue Circle Sour2 3 Green Square Bitter3 4 Pink Star SaltyPopped data:0 Oval1 Circle2 Square3 StarName: col 3, dtype: objectDataFrame after pop:col 1 col 2 col 40 1 Red Sweet1 2 Blue Sour2 3 Green Bitter3 4 Pink Salty
The code above creates a pandas DataFrame df from a dictionary d, prints the DataFrame, uses the .pop() method to remove the column col 3 and return it as a Pandas Series object, and then prints the popped data and the modified DataFrame.
Note: If the specified column label is not found in the
DataFrame, aKeyErrorwill be raised.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:Pandas on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to clean, analyze, and visualize data with Python and SQL.
- Includes 15 Courses
- With Certificate
- Beginner Friendly.55 hours