AboutBlogMediaTags

5 Ways to Delete a Column in Pandas DataFrame

Runcell Team,

5 Ways to Delete a Column in Pandas DataFrame

Cleaning a dataset often means removing columns that are redundant, duplicated, or just not useful for the analysis at hand. Pandas—the go-to Python library for tabular data—offers several ways to drop columns. Below are five practical approaches, complete with runnable examples and tips on when to reach for each one.

For the snippets below, start with the same sample DataFrame so you can see how each method behaves:

import pandas as pd # Sample data df = pd.DataFrame( { "name": ["Ada", "Bob", "Chloe"], "age": [29, 35, 42], "city": ["London", "Berlin", "New York"], "score": [88, 91, 77], } ) print(df)

1. Using drop()

drop() is the most flexible option. You can remove a single column or multiple columns, choose whether to modify the original DataFrame, and even drop rows by switching the axis.

# Drop a single column without touching the original df_without_city = df.drop(columns=["city"]) print(df_without_city) # Drop multiple columns in place df.drop(columns=["city", "score"], inplace=True) print(df)

2. Using the del statement

Python’s built-in del removes a column immediately from the DataFrame—no copy is created.

del df["score"] print(df)

3. Using pop()

pop() behaves like the list method of the same name: it removes the column and returns the data as a Series. This is perfect when you want to reuse the values elsewhere.

scores = df.pop("score") print(df) print(scores)

4. Column filtering

Instead of deleting columns, you can rebuild the DataFrame with only the fields you need. This technique avoids modifying the original object and makes the selected columns explicit.

subset = df[["name", "score"]] print(subset)

5. Using loc or iloc

loc and iloc allow you to filter columns by label or position. They are especially useful when you want to drop columns based on a condition.

# Keep every column except "score" using loc no_score = df.loc[:, df.columns != "score"] print(no_score) # Keep the first and last columns by index with iloc ends_only = df.iloc[:, [0, -1]] print(ends_only)

Summary table

MethodIn-place by default?Return valueBest use case
drop(columns=[...])No (unless inplace=True)New DataFrame or NoneFlexible deletions, batch operations
del df["col"]YesNoneQuick scripts where correctness of the column name is certain
df.pop("col")YesSeriesRemoving a column and reusing its values immediately
df[[...]] filteringNoNew DataFrameBuilding a clean subset without altering the source
df.loc / df.ilocNoNew DataFrameConditional column selection by label or position

Conclusion

Pick the deletion method that matches your workflow:

For large DataFrames, avoid unnecessary copies—prefer in-place operations when you no longer need the original column. With these five patterns, you can keep your pandas pipelines tidy and focused on the columns that matter.

© Runcell.RSS