Sub topic 14
Inserting, renaming, and dropping columns
This chapter assumes you can build a DataFrame, select a column by name, and add a column with df["name"] = .... Once you have derived several columns, you often need to put them where readers expect them, give them clear names, and remove the ones you no longer need.
Inserting a column at a position
Assignment always appends the new column at the end. DataFrame.insert(loc, column, value) places it at a chosen position instead. Positions start at 0, and the call changes the DataFrame in place and returns None.
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [1.5, 12.0, 30.0],
"qty": [10, 3, 2],
})
df.insert(1, "price_x2", df["price"] * 2)
print(df.columns.tolist())The output is ['item', 'price_x2', 'price', 'qty']. If the name already exists, insert() raises a ValueError. Pass allow_duplicates=True only if you really want two columns with the same name, which usually causes confusion later.
Renaming columns
rename() takes a mapping from old names to new names. It returns a new DataFrame and leaves names you did not mention unchanged.
df = df.rename(columns={"price_x2": "double_price", "qty": "quantity"})
print(df.columns.tolist())To change every name at once, pass a function. This is handy for tidying imported data.
df.columns = df.columns.str.upper()
print(df.columns.tolist())Assigning to df.columns replaces all names in place, so the new list must have exactly one name per column.
Dropping columns
drop(columns=[...]) returns a new DataFrame without the listed columns. A name that does not exist raises a KeyError. Pass errors="ignore" to skip missing names.
df = df.drop(columns=["DOUBLE_PRICE"])
df = df.drop(columns=["NOT_THERE"], errors="ignore")
print(df.columns.tolist())The output is ['ITEM', 'PRICE', 'QUANTITY']. To remove a column in place, you can use del df["PRICE"] or df.pop("PRICE"). The second form also returns the removed column as a Series.
Reordering columns
To reorder, select the columns in the order you want. This returns a new DataFrame.
df = df[["QUANTITY", "ITEM", "PRICE"]]Choosing a method
| Goal | Tool | Modifies in place? |
|---|---|---|
| Add at the end | `df["new"] = ...` | Yes |
| Add at a position | `df.insert(loc, name, values)` | Yes |
| Change names | `df.rename(columns=...)` | No, returns a copy |
| Remove columns | `df.drop(columns=...)` | No, returns a copy |
| Remove and keep one | `df.pop("name")` | Yes |
Common errors
- Duplicate name in
insert(): raisesValueError. Choose a unique name. - Wrong case or spaces in
drop(): raisesKeyError. Printdf.columns.tolist()to see the exact names. - Mismatched length when assigning
df.columns: raisesValueError. Provide one name per column.
Exercise
A DataFrame has columns ["a", "b", "c"]. Write code that inserts a column "a_plus_b" (the sum of a and b) as the first column, then drops column "c". What are the final column names?
Show answer
Use df.insert(0, "a_plus_b", df["a"] + df["b"]) and then df = df.drop(columns=["c"]). The final column names are ["a_plus_b", "a", "b"].
Exercise
Why does df = df.insert(0, "x", 1) leave you with a broken variable?
Show answer
insert() modifies the DataFrame in place and returns None, so the assignment overwrites df with None. Call df.insert(0, "x", 1) without assigning the result.