Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to delete a column of a dataframe using the 'pop' function in Python?
A Pandas DataFrame is a two-dimensional data structure where data is stored in tabular format with rows and columns. It can be visualized as an SQL table or Excel sheet. The pop() function provides an efficient way to delete a column while simultaneously returning its values.
Syntax
DataFrame.pop(item)
Parameters:
- item − The column name to be removed
Returns: The removed column as a Series
Example
Let's create a DataFrame and delete a column using the pop() function ?
import pandas as pd
my_data = {
'ab': pd.Series([1, 8, 7], index=['a', 'b', 'c']),
'cd': pd.Series([1, 2, 0, 9], index=['a', 'b', 'c', 'd']),
'ef': pd.Series([56, 78, 32], index=['a', 'b', 'c']),
'gh': pd.Series([66, 77, 88, 99], index=['a', 'b', 'c', 'd'])
}
my_df = pd.DataFrame(my_data)
print("Original DataFrame:")
print(my_df)
print("\nDeleting column 'cd' using pop() function:")
removed_column = my_df.pop('cd')
print(my_df)
print("\nRemoved column values:")
print(removed_column)
Original DataFrame:
ab cd ef gh
a 1.0 1 56.0 66
b 8.0 2 78.0 77
c 7.0 0 32.0 88
d NaN 9 NaN 99
Deleting column 'cd' using pop() function:
ab ef gh
a 1.0 56.0 66
b 8.0 78.0 77
c 7.0 32.0 88
d NaN NaN 99
Removed column values:
a 1
b 2
c 0
d 9
Name: cd, dtype: int64
Key Points
- The
pop()function modifies the original DataFrame in-place - It returns the removed column as a Series, which can be stored for later use
- If the column doesn't exist, it raises a
KeyError - NaN values appear when indices don't align across different Series
Comparison with Other Methods
| Method | Returns Column? | In-place? | Usage |
|---|---|---|---|
pop() |
Yes | Yes | When you need the removed column |
drop() |
No | Optional | General column removal |
del df[col] |
No | Yes | Quick deletion |
Conclusion
The pop() function is ideal when you need to remove a column and use its values elsewhere. It modifies the DataFrame in-place and returns the removed column as a Series for further processing.
Advertisements
