0
0
PandasHow-ToBeginner · 3 min read

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 named column_name from the DataFrame df.

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 del on a copy of a DataFrame instead of the original, so the original remains unchanged.
  • Confusing del with methods like drop() 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

ActionSyntaxNotes
Delete columndel df['column_name']Removes column in place, no return value
Check column exists'column_name' in df.columnsAvoids KeyError before deleting
Alternative methoddf.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.