Sub topic 14
Inserting, Renaming, and Dropping Columns
Earlier chapters showed how to create columns. This chapter covers the housekeeping that follows: placing a column where you want it, renaming columns, and removing the ones you no longer need. These steps keep a DataFrame readable and ready to export.
This chapter assumes you can build a DataFrame, select a column by name, and read basic Python syntax. Familiarity with df["name"] = ... assignment from the earlier chapters is helpful.
Where new columns go
Plain assignment with df["new"] = ... always appends the column at the right edge. That is fine for exploration. For a table that people will read, or one that feeds a system expecting a fixed layout, you often want control over position.
The starting frame for the examples below:
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [1.5, 12.0, 30.0],
"qty": [10, 3, 2],
})
print(df)Inserting at a chosen position with insert()
DataFrame.insert(loc, column, value) adds a column at integer position loc. Position 0 is the leftmost column.
df.insert(1, "price_x2", df["price"] * 2)
print(df.columns.tolist())The output is ['item', 'price_x2', 'price', 'qty']. The new column sits at index 1, and the existing columns shift right.
Three behaviors differ from ordinary assignment:
insert()changes the DataFrame in place and returnsNone. Writingdf = df.insert(...)replaces your frame withNone.- It raises
ValueErrorif the column name already exists. This protects you from overwriting by accident. Passallow_duplicates=Trueonly if you really want two columns with the same name, which is rarely a good idea. locmust be between 0 and the number of columns, inclusive. A value oflen(df.columns)appends at the end.
To place a new column right after an existing one without counting positions, look the position up:
pos = df.columns.get_loc("price") + 1
df.insert(pos, "price_x3", df["price"] * 3)
print(df.columns.tolist())get_loc returns the integer position of a label, so the code survives later changes to the column order.
Reordering existing columns
insert() only adds. To move a column that already exists, select the columns in the order you want. Selecting with a list returns a new DataFrame.
df = df[["item", "qty", "price", "price_x2", "price_x3"]]When you only want to move one column to the front, build the list from the rest:
front = ["qty"]
rest = [c for c in df.columns if c not in front]
df = df[front + rest]You can also use reindex(columns=...). It differs in one important way: a label that does not exist becomes a new column filled with NaN instead of raising an error.
| Approach | Missing label in the list | Result is |
|---|---|---|
| `df[[...]]` | Raises `KeyError` | New DataFrame |
| `df.reindex(columns=[...])` | Creates a `NaN` column | New DataFrame |
Prefer df[[...]] when a typo should fail loudly. Prefer reindex when you are aligning to a schema and want missing columns filled in.
Renaming columns
Renaming changes labels only. The data stays the same.
Renaming specific columns
Use rename() with a dictionary that maps old names to new names.
df = df.rename(columns={"qty": "quantity", "price_x2": "double_price"})
print(df.columns.tolist())rename() returns a new DataFrame by default. Keys that are not found are ignored silently, so a misspelled old name does nothing and raises no error. To catch typos, pass errors="raise":
df = df.rename(columns={"quantity": "units"}, errors="raise")With errors="raise", a key that matches no column raises KeyError.
Renaming every column with a function
Pass a function instead of a dictionary to transform all names at once. This is the usual way to standardize messy headers.
messy = pd.DataFrame({" Unit Price ": [1, 2], "Order Qty": [3, 4]})
clean = messy.rename(columns=lambda c: c.strip().lower().replace(" ", "_"))
print(clean.columns.tolist())The result is ['unit_price', 'order_qty'].
The same cleanup works with the .str accessor on the column index. Use this form when you want to assign the names back directly:
messy.columns = messy.columns.str.strip().str.lower().str.replace(" ", "_")Assigning to df.columns replaces all labels at once. The list you assign must have exactly one name per column, in the current order. A list of the wrong length raises ValueError. Because it relies on position, it is easy to mislabel columns after a reorder. Use rename() when you only change some names.
Adding a prefix or suffix
add_prefix() and add_suffix() are shortcuts for bulk renames. They help before joining two tables whose column names would otherwise collide.
renamed = df.add_prefix("src_")
print(renamed.columns.tolist())Renaming inside a method chain
Because rename() returns a new frame, it fits into a chain with assign():
result = (
df
.assign(total=lambda d: d["price"] * d["units"])
.rename(columns={"total": "line_total"})
)For a single use, you could name the column line_total directly in assign(). Renaming is useful when the name comes from a helper function or when you need a temporary name inside the chain.
Dropping columns
Removing columns shrinks the frame and prevents leftover helper columns from reaching your output.
drop()
drop(columns=...) accepts one label or a list of labels:
df = df.drop(columns=["price_x3", "double_price"])
print(df.columns.tolist())Always use the columns= keyword. The older form df.drop("name", axis=1) works but is easier to misread, since without axis=1 pandas treats the label as a row label.
Like rename(), drop() returns a new DataFrame. If a label is missing, it raises KeyError. When the column may or may not exist, for example in a function that runs on varied inputs, ignore the missing ones:
df = df.drop(columns=["notes"], errors="ignore")del and pop()
Two other tools remove a column in place:
tmp = df.copy()
tmp["scratch"] = 0
del tmp["scratch"] # removes the column, returns nothing
tmp["scratch2"] = 1
removed = tmp.pop("scratch2") # removes the column and returns it as a SeriesUse pop() when you want to take a column out and keep using it, such as separating a target column from features.
Keeping instead of dropping
When you want only a few columns out of many, listing the ones to keep is clearer than listing the ones to drop. It also stays correct when new columns appear upstream.
subset = df[["item", "units"]]To keep columns by pattern, use filter():
wide = pd.DataFrame({"a_1": [1], "a_2": [2], "b_1": [3]})
only_a = wide.filter(like="a_")
only_b = wide.filter(regex=r"^b_")Choosing between in-place and returning methods
The tools split into two groups.
| Tool | Modifies the original | Returns |
|---|---|---|
| `df["c"] = ...` | Yes | Nothing |
| `df.insert(...)` | Yes | `None` |
| `del df["c"]` | Yes | Nothing |
| `df.pop("c")` | Yes | The removed Series |
| `df.rename(...)` | No | New DataFrame |
| `df.drop(columns=...)` | No | New DataFrame |
| `df.assign(...)` | No | New DataFrame |
Methods that return a new frame chain naturally. In-place methods break a chain because they return None or something that is not a DataFrame. Mixing the two styles in one pipeline is a common source of bugs: a later line may act on a frame you thought was unchanged.
Common errors
ValueError: cannot insert price_x2, already exists. The name is already taken. Choose another name, drop the old column first, or assign withdf["price_x2"] = ...to overwrite.- A rename that does nothing. The key has different spacing or case than the real column name. Print
df.columns.tolist()to see the exact labels, or useerrors="raise". dfbecomesNone. You assigned the result of an in-place method such asinsert().- A dropped column comes back. You called
df.drop(columns=[...])without assigning the result. The original frame is unchanged. - Wrong labels after assigning
df.columns. The new list was in a different order from the data. Prefer a dictionary or a function inrename().
Putting it together
A typical cleanup pass combines all three tasks:
raw = pd.DataFrame({
" Item Name ": ["pen", "book"],
"Unit Price": [1.5, 12.0],
"Qty": [10, 3],
"tmp_flag": [0, 1],
})
tidy = (
raw
.rename(columns=lambda c: c.strip().lower().replace(" ", "_"))
.drop(columns=["tmp_flag"])
.assign(total=lambda d: d["unit_price"] * d["qty"])
)
tidy.insert(0, "row_id", range(1, len(tidy) + 1))
print(tidy)The chain renames, removes the helper column, and adds a computed column. The final insert() runs separately because it works in place, so it cannot sit inside the chain.
Exercise
You have df with columns ["id", "name", "score", "debug"]. Write code that makes a new DataFrame with the columns renamed to upper case, the debug column removed, and a column score_pct (score divided by 100) placed immediately after SCORE. The original df must stay unchanged.
Show answer
out = df.drop(columns=["debug"]).rename(columns=str.upper)
out.insert(out.columns.getloc("SCORE") + 1, "SCOREPCT", out["SCORE"] / 100)
Here drop and rename return new frames, so df is untouched. insert then runs on the new frame out, which is safe. Using get_loc("SCORE") + 1 puts the new column right after SCORE. The new column name is upper case here to match the rest; naming it score_pct as the task states is also acceptable.
Exercise
A colleague writes df = df.insert(0, "id", range(len(df))) and then gets AttributeError: 'NoneType' object has no attribute 'columns'. What went wrong, and how do you fix it?
Show answer
insert() modifies the DataFrame in place and returns None, so the assignment replaces df with None. Remove the assignment: df.insert(0, "id", range(len(df))).