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
Write a program in Python to remove one or more than one columns in a given DataFrame
Sometimes you need to remove one or more columns from a Pandas DataFrame. Python provides several methods to accomplish this: using del statement, pop() method, and drop() method.
Using del Statement
The del statement permanently removes a single column from the DataFrame ?
import pandas as pd
data = [[1, 2, 3], [4, 5, 6]]
df = pd.DataFrame(data, columns=('one', 'two', 'three'))
print("Before deletion:")
print(df)
del df['one']
print("\nAfter deletion:")
print(df)
Before deletion: one two three 0 1 2 3 1 4 5 6 After deletion: two three 0 2 3 1 5 6
Using pop() Method
The pop() method removes a column and returns its values as a Series ?
import pandas as pd
data = [[1, 2, 3], [4, 5, 6]]
df = pd.DataFrame(data, columns=('one', 'two', 'three'))
print("Before deletion:")
print(df)
removed_column = df.pop('one')
print("\nRemoved column:")
print(removed_column)
print("\nAfter deletion:")
print(df)
Before deletion: one two three 0 1 2 3 1 4 5 6 Removed column: 0 1 1 4 Name: one, dtype: int64 After deletion: two three 0 2 3 1 5 6
Using drop() Method for Multiple Columns
The drop() method is most flexible and can remove one or multiple columns. Use inplace=True to modify the original DataFrame ?
import pandas as pd
data = [[1, 2, 3], [4, 5, 6]]
df = pd.DataFrame(data, columns=('one', 'two', 'three'))
print("Before deletion:")
print(df)
df.drop(columns=['one', 'two'], inplace=True)
print("\nAfter deleting two columns:")
print(df)
Before deletion: one two three 0 1 2 3 1 4 5 6 After deleting two columns: three 0 3 1 6
Comparison
| Method | Multiple Columns? | Returns Data? | Best For |
|---|---|---|---|
del |
No | No | Simple single column removal |
pop() |
No | Yes (Series) | When you need the removed data |
drop() |
Yes | No | Multiple columns or flexible operations |
Conclusion
Use del for simple single column removal, pop() when you need the removed data, and drop() for removing multiple columns or more control over the operation.
Advertisements
