Remove pandas columns by name
How to remove columns by name in pandas with drop(columns=...), what the operation changes, how it compares with del, pop and column selection, and what to check before exporting.
Removing a column by name in pandas usually means calling DataFrame.drop with the columns argument. The method is short, but a few details decide whether the result is what you intended. These include whether the change is saved, how names are matched, and what happens when a name is missing. This review covers what the operation changes, when it fits, how it compares with the alternatives, and what to check before you share the output.
Short answer: is drop(columns=...) the right tool?
For most work, reassigning the result of df.drop(columns=[...]) is the clearest option. The names you remove are written out explicitly, the code reads plainly, and the original DataFrame object is left untouched unless you overwrite the variable. The main tradeoff is error handling. By default, drop raises a KeyError when a listed name does not exist. That catches typos, but it gets in the way when input files vary. Passing errors='ignore' removes the error and also removes that protection. In two situations, selecting the columns you want to keep is the better choice: when the wanted set is smaller or more stable than the unwanted set, or when column order matters. For a single manual edit to a small delimited file that you will never repeat, a spreadsheet or text editor may be simpler. pandas is most useful when the step has to be repeatable.
import pandas as pd
df = pd.DataFrame({
'id': [1, 2],
'name': ['Ana', 'Ben'],
'temp_score': [0.4, 0.9],
})
df = df.drop(columns=['temp_score'])
print(df.columns.tolist())
# ['id', 'name']
What removing a column actually changes
drop works on the DataFrame in memory. It does not touch the file you loaded. By default it returns a new DataFrame. A frequent point of confusion is calling df.drop(columns=['x']) without assigning the result, which looks as if nothing happened. With inplace=True, the method modifies the existing object and returns None. Writing df = df.drop(..., inplace=True) therefore replaces your data with None. The source CSV or database table stays as it was until you write the result back out.
Removing a column is different from hiding it. Display settings and the Styler's hide option in recent pandas versions only change how a table is rendered, and the column is still in the data. If the column must be absent from later calculations or exported files, drop it. Hiding it is not enough.
Name matching is exact and case-sensitive. A header read from a CSV as 'Temp_Score ' (capitalized, with a trailing space) will not match 'temp_score', and drop will raise a KeyError. When several columns share the same label, dropping that label removes all of them. For columns with a MultiIndex, the level argument selects which level the name is matched against. Leaving out both columns= and axis=1 makes drop look for the label among the rows, which is the default axis. The resulting "not found in axis" error is a common sign of this mistake. Using the columns keyword avoids the ambiguity.
Equivalent approaches and how they differ
| Approach | What it does | Returns | Notes |
| df.drop(columns=['a', 'b']) | Removes the named columns | New DataFrame | KeyError for missing names unless errors='ignore' |
| df.drop('a', axis=1) | Same result, older style | New DataFrame | Omitting axis=1 targets rows instead |
| del df['a'] | Removes one column in place | Nothing | Mutates the object; one name at a time |
| df.pop('a') | Removes one column in place | The removed column as a Series | Useful when you still need the values |
| df[['id', 'name']] | Keeps only the listed columns | New DataFrame | KeyError for missing names; order follows the list |
| df.loc[:, ~df.columns.isin(['a', 'b'])] | Keeps everything except the listed names | New DataFrame | No error when a listed name is absent |
| df.drop(columns=df.filter(regex='^temp_').columns) | Removes columns whose names match a pattern | New DataFrame | Check which names match before relying on it |
# Normalize stray whitespace in headers before matching by name
df.columns = df.columns.str.strip()
# Tolerate names that may not be present in every input
df = df.drop(columns=['temp_score', 'maybe_missing'], errors='ignore')
# Pattern-based removal: inspect the matches first
to_remove = df.filter(regex='^temp_').columns
print(list(to_remove))
df = df.drop(columns=to_remove)
Will the result stay usable after export or sharing?
Once you write the trimmed DataFrame with to_csv or a similar method, the removed columns are not in the output file and cannot be recovered from it. Keep the original source, or write to a new filename. drop keeps the relative order of the remaining columns. Consumers that read columns by name are unaffected unless they need a removed column. Consumers that read columns by position will see the positions shift. Also note that to_csv writes the index as an extra leading column unless you pass index=False. That extra column can look as if a column was added back.
Copying a table out of a notebook is not the same as exporting it. Display settings can truncate wide or long output, so the copied text may be incomplete. If others need the data, an exported plain-text CSV or tab-separated file is generally more portable than a screenshot of notebook output. People can search, edit and re-import the text, and assistive technology can read it as text, which an image without a text alternative does not allow.
This review rests on documented pandas behavior. It does not include tests against particular pandas versions, spreadsheet applications or screen readers. If you work in an older environment, check the documentation for your installed version to confirm that the parameters shown here are supported. Also check how your destination application handles delimiters and encoding.
Choosing an approach
- Use drop(columns=[...]) and reassign the result when you know the unwanted names and want typos to fail loudly.
- Add errors='ignore' only when inputs legitimately differ in which columns they contain.
- Select the columns to keep when the wanted set is short, must follow a fixed order, or should exclude unexpected new columns.
- Use pop when you need the removed column's values for something else.
- Use pattern-based removal only after printing the names it matches.
- Strip whitespace from headers first when column names come from external files.