Select all pandas columns except specified columns

How to select every pandas DataFrame column except one or several: drop, loc with isin, Index.difference and list comprehensions, with tradeoffs in column order and missing-label handling.

Excluding a few columns from a pandas DataFrame is a common step before exporting a table, training a model or sharing a cleaned dataset. Several idioms do it, and they differ in three ways that matter: whether column order is kept, what happens when an excluded name does not exist, and whether the original DataFrame is changed. This review compares the main options using documented pandas behavior. No benchmark measurements or environment-specific tests were supplied, so performance claims are left out.

Short recommendation

For most cases, use df.drop(columns=[...]). It reads clearly, keeps the remaining columns in their original order, and raises an error if you name a column that does not exist, which catches typos early. If the list of excluded names may contain columns that are not present, pass errors="ignore" or use a boolean mask with isin. Avoid Index.difference when column order matters unless you pass sort=False.

Writing out the columns you want to keep is preferable to exclusion when the set of kept columns is small and stable, or when the output feeds a fixed schema such as a CSV consumed by another system. An explicit keep list fails loudly if a column disappears and does not silently pass through new columns added upstream.

Example data

The examples below use a small DataFrame whose columns are deliberately not in alphabetical order, so differences in ordering are visible.

import pandas as pd

df = pd.DataFrame({
    "name": ["a", "b"],
    "id": [1, 2],
    "score": [0.5, 0.9],
    "notes": ["x", "y"],
})

Ways to exclude one column

# Option 1: drop
df.drop(columns="notes")

# Option 2: boolean mask on the column index
df.loc[:, df.columns != "notes"]

# Both return columns: ['name', 'id', 'score']

The comparison df.columns != "notes" produces a boolean array with one value per column, and loc keeps the columns where it is True. It only handles a single name; for several names, use isin.

Selecting columns not in a list

exclude = ["notes", "score"]

# drop: raises KeyError if a name is missing
df.drop(columns=exclude)

# drop, tolerating missing names
df.drop(columns=exclude, errors="ignore")

# boolean mask: missing names are ignored
df.loc[:, ~df.columns.isin(exclude)]

# list comprehension: missing names are ignored
df[[c for c in df.columns if c not in exclude]]

# All of the above return columns: ['name', 'id']

Index.difference is often suggested for the same task, but by default it attempts to sort the result. With this example, df[df.columns.difference(["notes"])] returns the columns as ['id', 'name', 'score'], not in their original order. Passing sort=False keeps the original order.

df[df.columns.difference(["notes"])]              # columns: ['id', 'name', 'score']
df[df.columns.difference(["notes"], sort=False)]  # columns: ['name', 'id', 'score']

How the options compare

Method | Keeps original column order | If an excluded name is missing | Notes
df.drop(columns=list) | Yes | Raises KeyError | Add errors="ignore" to skip missing names
df.loc[:, df.columns != name] | Yes | No error | Single name only
df.loc[:, ~df.columns.isin(list)] | Yes | No error | Works for any number of names
df[[c for c in df.columns if c not in list]] | Yes | No error | Plain Python; easy to add extra conditions
df[df.columns.difference(list)] | No, sorts by default | No error | Use sort=False to keep order
df.filter(regex=pattern) | Yes | Not applicable | Pattern-based; useful for excluding by prefix or suffix

What the selection actually changes

None of these idioms alter the values in the remaining columns or the row index. They return a new DataFrame containing a subset of the columns; the original df is unchanged unless you reassign the result or call drop with inplace=True. Reassigning (df = df.drop(columns=...)) is generally clearer than inplace=True and makes the change visible in the code.

If you plan to modify the subset afterward, older pandas versions may emit a SettingWithCopyWarning because it can be unclear whether the subset shares data with the original. Calling .copy() on the result makes the independence explicit. Newer pandas releases with Copy-on-Write behavior handle this differently; check the documentation for the version you run rather than relying on the warning alone.

Edge cases that affect usability

  • Duplicate column names: drop removes every column with that label, and an isin mask excludes all of them as well. If you need to remove only one of several identically named columns, select by position with iloc instead.
  • MultiIndex columns: drop accepts a level argument, for example df.drop(columns="notes", level=1), to remove a label from one level of the hierarchy. A plain equality mask compares whole tuples, not individual levels.
  • Non-string labels: integer or mixed-type column labels work with drop and isin. Index.difference with its default sort may fall back to an unsorted result if labels cannot be compared, so order is harder to predict.
  • Typos: only drop without errors="ignore" reports a misspelled name. The mask, list comprehension and difference approaches silently keep the column you meant to remove.
  • Export: once columns are excluded and the result is written with to_csv or a similar method, the omitted columns are absent from the file. If downstream consumers expect a fixed column order, prefer a method that preserves order or select an explicit keep list.

Choosing by situation

  • Excluding known, required columns from a stable dataset: df.drop(columns=[...]).
  • Excluding a list that may include names not present in every file: df.drop(columns=[...], errors="ignore") or df.loc[:, ~df.columns.isin([...])].
  • Excluding by naming pattern, such as all columns ending in a suffix: df.filter(regex=...) or a list comprehension with a string test.
  • Producing output for a fixed schema: list the columns to keep explicitly instead of excluding.

Evidence gaps

The behavior described here reflects pandas' documented semantics for drop, loc, isin, Index.difference and filter. No version-specific test results or performance measurements were supplied, so this review makes no claims about relative speed on large DataFrames. Defaults can change between releases, so confirm behavior such as sorting and copy semantics against the documentation for your installed version.