Q&A library Python

How do I drop columns or rows in pandas?

Python Beginner columnsdroprows

Short answer

Use drop with the columns argument to remove columns and the index argument to remove rows. It returns a new frame, so reassign, and errors="ignore" stops it raising on names that are not there.

The short version

Use df.drop(columns=["a", "b"]) to remove columns and df.drop(index=[0, 1]) to remove rows by label. It returns a new frame, so assign the result back. Pass errors="ignore" if a name might legitimately be absent and you do not want an exception.

Dropping columns

import pandas as pd

df = pd.DataFrame({"city": ["Leeds"], "amount": [10], "temp": [15]})

df = df.drop(columns=["temp"])
print(df.columns.tolist())   # ['city', 'amount']

The columns= form is explicit and readable. You will also see the older df.drop("temp", axis=1), which means the same thing (axis 1 is the column axis), but the keyword version is clearer and less error-prone.

Dropping rows

Rows are dropped by their index label, not their position.

df.drop(index=[0])          # removes the row labelled 0

Be careful: after filtering or sorting, index labels no longer match positions, so drop(index=[0]) may not remove the first row. If you mean "remove by position", select the ones you want to keep with iloc instead.

Reassign or use inplace

drop returns a new frame and leaves the original alone, so this line does nothing lasting.

df.drop(columns=["temp"])   # result discarded!

Either reassign (df = df.drop(...)) or pass inplace=True. Reassigning is usually clearer and works naturally in a method chain.

Handling names that may not exist

Dropping a column that is not there raises a KeyError. When you are cleaning files that vary, errors="ignore" makes the drop safe.

df.drop(columns=["temp", "notes"], errors="ignore")

This removes whichever of those exist and quietly skips the rest, which is exactly what you want when tidying inconsistent inputs.

Keeping instead of dropping

Often it is clearer to state what you want to keep, especially when you are discarding many columns.

df = df[["city", "amount"]]

This also fixes the column order, and it fails loudly if a column you expected is missing, which is usually a good thing.

Dropping by condition

To remove rows matching a condition, filter for the opposite rather than computing labels to drop.

df = df[df["amount"] > 0]        # keep the good rows

This reads more naturally than finding the offending index labels and passing them to drop, and it is the idiomatic way to remove rows in pandas.

Dropping missing values

For removing rows or columns because of missing data, dropna is the purpose-built tool, with subset to limit which columns count and axis=1 to drop columns instead of rows.

Enjoying these?

Go from piecing together answers to real fluency.

Our courses take you from looking things up to doing the work with confidence, step by step on real data.

Browse the courses