Select all pandas columns except specified columns

Ways to keep every pandas column except a few: drop, boolean masks, Index.difference, filter and read_csv usecols, with tradeoffs on order and missing labels.

Excluding a handful of columns from a pandas DataFrame is a common step before exporting delimited text, training a model or building a report. pandas has no dedicated "except" selector, so there are several ways to do it. They differ in how they treat column order, labels that do not exist, duplicate names and pattern-based exclusions. This review explains what each approach changes and when each one is the right choice.

Short recommendation

For most cases, use df.drop(columns=[...]). It is readable, keeps the remaining columns in their original order and fails loudly if you misspell a column name. Use a boolean mask with isin when the excluded names may or may not be present. Use filter or select_dtypes when you are excluding by pattern or data type rather than by name. When the data comes from a CSV file and the unwanted columns are large, exclude them at read time with usecols so they are never loaded.

The main tradeoff is between strictness and tolerance. A strict method catches typos and schema changes early. A tolerant method keeps a pipeline running when an optional column is absent, but it can hide mistakes. An explicit list of columns to keep is preferable to an exclusion when the output feeds a fixed downstream format: a new column added upstream will then not appear unexpectedly in your export.

What the selection actually changes

Every method below returns a DataFrame with fewer columns. Cell values, data types and the row index are left unchanged. The word "inverse" in this context means logical negation of a selection, as with the ~ operator on a boolean mask. It does not reverse column order or alter any text. The differences between methods lie in which columns survive, the order they appear in, and what happens when a requested label is missing.

The examples use this small frame:

import pandas as pd

df = pd.DataFrame({
    'id': [1, 2],
    'name': ['Ana', 'Ben'],
    'temp_score': [0.4, 0.9],
    'city': ['Austin', 'Boston'],
})
exclude = ['temp_score']

drop: the default choice

result = df.drop(columns=exclude)
list(result.columns)
# ['id', 'name', 'city']

drop returns a new DataFrame and preserves the original column order. If any name in the list is not a column, it raises a KeyError. Passing errors='ignore' suppresses that error and skips the missing names. If the frame contains duplicate column names, dropping a label removes every column with that label. The older form df.drop(exclude, axis=1) behaves the same way. The columns= keyword is clearer to read.

Boolean mask with isin: tolerant of missing names

result = df.loc[:, ~df.columns.isin(exclude)]
list(result.columns)
# ['id', 'name', 'city']

This keeps original order and never raises an error for names that are not present. It also works when columns are duplicated, because the mask is evaluated position by position. The cost is readability, and a misspelled exclusion is silently ignored.

Index.difference: watch the column order

result = df[df.columns.difference(exclude)]
list(result.columns)
# ['city', 'id', 'name']

result = df[df.columns.difference(exclude, sort=False)]
list(result.columns)
# ['id', 'name', 'city']

difference is concise and tolerant of missing names. By default it sorts the resulting labels when they can be sorted, so the output columns are reordered alphabetically. That matters if the result is written to a delimited file with a fixed column layout. Passing sort=False keeps the original order. difference also behaves like a set operation, so it is not a good fit for frames with duplicate column names.

List comprehension: explicit and order-preserving

result = df[[c for c in df.columns if c not in exclude]]
list(result.columns)
# ['id', 'name', 'city']

This is plain Python with no pandas-specific behavior to remember. It keeps the original order and ignores missing names. It is a reasonable choice when the exclusion rule is more complex than a fixed list, such as combining a name list with a condition on the column name.

Excluding by pattern or data type

# Drop every column whose name starts with 'temp_'
result = df.filter(regex=r'^(?!temp_)')
list(result.columns)
# ['id', 'name', 'city']

# Drop all numeric columns
result = df.select_dtypes(exclude='number')
list(result.columns)
# ['name', 'city']

filter with a negative lookahead keeps columns that do not match a prefix or pattern. The regex is less obvious to readers, so a short comment helps. select_dtypes is useful when the rule is "everything except numbers" or "everything except dates". It depends on columns having the expected dtypes, so a numeric column stored as text will not be excluded.

Excluding columns while reading a CSV

exclude = {'temp_score', 'notes'}
df = pd.read_csv('data.csv', usecols=lambda c: c not in exclude)

read_csv accepts a callable for usecols. pandas evaluates it against each column name and keeps the columns for which it returns True. The unwanted columns are skipped during parsing instead of being loaded and then dropped. Names in the exclusion set that do not appear in the file are simply never matched, so this approach is tolerant by nature. No measurements of memory or speed savings were supplied for this review, so the size of the benefit for a particular file is not quantified here.

MultiIndex columns

For hierarchical column labels, drop accepts a level argument, for example df.drop(columns='temp', level=1), to remove every column with that label at the given level. A boolean mask built from df.columns.get_level_values(1) is the tolerant alternative.

Comparison at a glance

Method | Keeps original order | Missing names | Duplicate column names | Best for
df.drop(columns=...) | Yes | KeyError unless errors='ignore' | Removes all matches | Most everyday cases
df.loc[:, ~df.columns.isin(...)] | Yes | Ignored | Handled by position | Optional columns
df.columns.difference(...) | Only with sort=False | Ignored | Not suitable | Short set-style code
List comprehension | Yes | Ignored | Keeps duplicates not excluded | Custom rules
df.filter(regex=...) | Yes | Not applicable | Matches by pattern | Prefix or pattern rules
df.select_dtypes(exclude=...) | Yes | Not applicable | Matches by dtype | Type-based rules
read_csv(usecols=callable) | Yes | Ignored | Depends on file headers | Skipping columns at load time

Will the result stay usable after copying, saving or sharing?

The selected frame is ordinary tabular data, so it carries no hidden formatting or special characters that could break copy and paste. The practical risks are about copies, column order and export settings.

  • Copies versus views: drop returns a new object. A selection made with loc or bracket indexing may share data with the original in older pandas behavior, and assigning into it can trigger SettingWithCopyWarning. Calling .copy() on the result before modifying it avoids ambiguity. Under Copy-on-Write, the default in pandas 3.0, modifying a derived frame does not change the original.
  • Avoid inplace=True: df.drop(columns=..., inplace=True) mutates the original and returns None. A common bug is assigning that None back to a variable.
  • Column order in exports: if a downstream tool reads a CSV by position rather than by header, an unexpected reordering, for example from Index.difference with default sorting, can misalign data without raising any error.
  • Index in exports: to_csv writes the row index by default. Pass index=False if the receiving system expects only the selected data columns.
  • New upstream columns: an exclusion list lets new columns through automatically. If the destination expects a fixed schema, select an explicit list of columns to keep instead, or pass columns=[...] to to_csv.

Accessibility, screen readers and search indexing are not affected by how columns are selected in pandas. They depend on how the final table is published, such as an HTML table with proper headers versus an image of a table. No documentation or tests for specific destinations or assistive technologies were supplied, so this review makes no claims about how particular tools render exported files.

Choosing a method

Start with drop(columns=...) for clarity and early error detection. Switch to an isin mask or a list comprehension when the excluded columns are optional. Use filter or select_dtypes when the rule is a pattern or a type. Use read_csv with a usecols callable when you want to avoid loading the columns at all. Whatever you choose, check the resulting column order before writing delimited output, and prefer an explicit keep-list when the consumer depends on a fixed layout.