How to Use del to Delete a Column in pandas DataFrame
You can use
del followed by the DataFrame and column name in brackets to delete a column in pandas, like del df['column_name']. This removes the column permanently from the DataFrame.Syntax
The syntax to delete a column using del in pandas is:
del df['column_name']: Deletes the column namedcolumn_namefrom the DataFramedf.
Here, df is your pandas DataFrame, and 'column_name' is the exact name of the column you want to remove.
python
del df['column_name']
Example
This example shows how to create a DataFrame and delete a column using del. The column is removed permanently from the DataFrame.
python
import pandas as pd # Create a sample DataFrame df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'City': ['New York', 'Los Angeles', 'Chicago'] }) print('Original DataFrame:') print(df) # Delete the 'Age' column del df['Age'] print('\nDataFrame after deleting Age column:') print(df)
Output
Original DataFrame:
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago
DataFrame after deleting Age column:
Name City
0 Alice New York
1 Bob Los Angeles
2 Charlie Chicago
Common Pitfalls
Common mistakes when using del to remove columns include:
- Trying to delete a column that does not exist, which raises a
KeyError. - Using
delon a copy of a DataFrame instead of the original, so the original remains unchanged. - Confusing
delwith methods likedrop()which can return a new DataFrame instead of modifying in place.
Always ensure the column name exists and you are working on the correct DataFrame.
python
import pandas as pd df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) # Wrong: deleting a non-existing column # del df['C'] # This will raise KeyError # Correct: check if column exists before deleting if 'C' in df.columns: del df['C'] else: print('Column C does not exist.')
Output
Column C does not exist.
Quick Reference
| Action | Syntax | Notes |
|---|---|---|
| Delete column | del df['column_name'] | Removes column in place, no return value |
| Check column exists | 'column_name' in df.columns | Avoids KeyError before deleting |
| Alternative method | df.drop('column_name', axis=1, inplace=True) | Also deletes column in place |
Key Takeaways
Use del df['column_name'] to delete a column from a pandas DataFrame permanently.
Ensure the column exists before using del to avoid KeyError exceptions.
del modifies the original DataFrame and does not return a new one.
For safer deletion, check column presence or use df.drop() with inplace=True.
del is a simple and direct way to remove columns when you want to modify the DataFrame in place.