How to Use pop in pandas: Remove and Return Columns Easily
In pandas, the
pop method removes a column from a DataFrame and returns it as a Series. Use df.pop('column_name') to extract and delete the column in one step.Syntax
The pop method syntax is simple:
df.pop(item): Removes the column nameditemfrom the DataFramedfand returns it as a Series.
Parameters:
item: The label of the column to remove.
Returns: The removed column as a pandas Series.
python
df.pop(item)
Example
This example shows how to use pop to remove a column from a DataFrame and get it back as a Series.
python
import pandas as pd data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'City': ['NY', 'LA', 'Chicago']} df = pd.DataFrame(data) # Remove 'Age' column and get it as a Series age_series = df.pop('Age') print('DataFrame after pop:') print(df) print('\nPopped column as Series:') print(age_series)
Output
DataFrame after pop:
Name City
0 Alice NY
1 Bob LA
2 Charlie Chicago
Popped column as Series:
0 25
1 30
2 35
Name: Age, dtype: int64
Common Pitfalls
Common mistakes when using pop include:
- Trying to pop a column that does not exist, which raises a
KeyError. - Expecting
popto work on rows; it only works on columns. - Not realizing that
popmodifies the original DataFrame by removing the column.
Always check if the column exists before popping or handle exceptions.
python
import pandas as pd df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) # Wrong: popping a non-existent column try: df.pop('C') except KeyError as e: print(f'Error: {e}') # Right: check before popping if 'B' in df.columns: col = df.pop('B') print('Popped column B:', col)
Output
Error: 'C'
Popped column B: 0 3
1 4
Name: B, dtype: int64
Quick Reference
| Method | Description | Returns | Modifies Original DataFrame |
|---|---|---|---|
| pop(item) | Removes and returns the column named item | Series of the removed column | Yes |
Key Takeaways
Use df.pop('column_name') to remove and get a column as a Series in one step.
pop modifies the original DataFrame by deleting the specified column.
pop raises KeyError if the column does not exist; check before popping.
pop only works on columns, not rows.
The returned object from pop is a pandas Series of the removed column.