Rename, Drop & Reorder
Rename columns and index labels, remove columns or rows with drop, del and pop, and reorder columns into the order you want.
Watch the lesson
1 video on CodeWithMunnaX
Raw data rarely comes with tidy column names or only the columns you need. A CSV may call a column " Player Name" (with a leading space), include ten columns you never use, and put the important ones last. This topic covers the three clean-up tools you use on almost every dataset: rename, drop, and reorder.
Sample table:
text
player team runs balls sixes
0 Shubman Gill GT 890 564 33
1 Faf du Plessis RCB 730 475 36
2 Virat Kohli RCB 639 457 16
3 Rinku Singh KKR 474 317 29Definition
rename changes column names and/or index labels using a mapping (dict) or a function. drop removes rows or columns by label. Reordering means selecting the columns in a new order. All three return a new DataFrame and leave the original unchanged (unless you reassign it).
- Mapping — a dict
{"old": "new"}; only the names you mention change. - By label —
dropworks with names/labels, not positions (usedf.columns[i]ordf.index[i]to translate a position). - Return a new DataFrame — write
df = df.drop(...). (inplace=Trueexists but is discouraged.)
Syntax
python
df.rename(columns={"old": "new"}, index={old_label: new_label}, errors="ignore")
df.columns = [list of all new names] # replace every name at once
df.drop(columns=[...]) # drop columns
df.drop(index=[...]) # drop rows by label
df.drop(labels, axis=0 | 1, errors="raise") # older style
del df["col"] # delete a column in place
df.pop("col") # remove a column in place AND return it
df[["c3", "c1", "c2"]] # reorder by selecting
df.reindex(columns=[...]) # reorder; unknown names -> NaN column| Function / parameter | Meaning | Default |
|---|---|---|
rename(columns=...) | dict or function applied to column names | None |
rename(index=...) | dict or function applied to row labels | None |
rename(errors=...) | "raise" if a key isn't found | "ignore" |
drop(columns=...) | column name or list of names to remove | None |
drop(index=...) | row label or list of labels to remove | None |
drop(labels, axis=...) | axis=0 rows, axis=1 columns | axis=0 |
drop(errors=...) | "ignore" silently skips missing labels | "raise" |
reindex(columns=...) | new column order; unknown names become NaN columns | — |
Example — rename columns and index labels
python
r = df.rename(columns={"player": "batter", "runs": "total_runs"})
print(r)
print(df.columns.tolist())
print(df.rename(index={0: "first", 3: "last"}))text
batter team total_runs balls sixes
0 Shubman Gill GT 890 564 33
1 Faf du Plessis RCB 730 475 36
2 Virat Kohli RCB 639 457 16
3 Rinku Singh KKR 474 317 29
['player', 'team', 'runs', 'balls', 'sixes']
player team runs balls sixes
first Shubman Gill GT 890 564 33
1 Faf du Plessis RCB 730 475 36
2 Virat Kohli RCB 639 457 16
last Rinku Singh KKR 474 317 29How it works: only the keys you mention are renamed. The original df still has its old names — rename returned a new DataFrame (r). Passing a function renames every name: df.rename(columns=str.upper) → ['PLAYER', 'TEAM', 'RUNS', 'BALLS', 'SIXES'].
Example — clean messy column names in one line
python
messy = pd.DataFrame(columns=[" Player Name", "Team ", "Total Runs"])
messy.columns = messy.columns.str.strip().str.lower().str.replace(" ", "_")
print(messy.columns.tolist())text
['player_name', 'team', 'total_runs']How it works: df.columns is an Index of strings, so it supports the .str methods: strip removes outer spaces, lower lowercases, replace swaps spaces for underscores. Assigning to df.columns replaces all names — the list must have exactly as many names as there are columns, otherwise ValueError: Length mismatch: Expected axis has 5 elements, new values have 2 elements.
Example — drop columns and rows
python
print(df.drop(columns=["balls", "sixes"]))
print(df.drop(index=[1, 3]))text
player team runs
0 Shubman Gill GT 890
1 Faf du Plessis RCB 730
2 Virat Kohli RCB 639
3 Rinku Singh KKR 474
player team runs balls sixes
0 Shubman Gill GT 890 564 33
2 Virat Kohli RCB 639 457 16How it works: columns= and index= make it obvious what you are dropping. The older form df.drop(["balls"], axis=1) does the same as df.drop(columns=["balls"]), and df.drop([0]) drops the row labelled 0 (axis 0 is the default). Note the remaining rows keep their original labels (0, 2) — they are not renumbered.
Dropping a name that doesn't exist raises KeyError: "['wickets'] not found in axis"; add errors="ignore" to skip it silently.
Example — drop rows by a condition
python
print(df.drop(df[df["team"] == "RCB"].index))text
player team runs balls sixes
0 Shubman Gill GT 890 564 33
3 Rinku Singh KKR 474 317 29df[df["team"] == "RCB"].index gives the labels of RCB rows, and drop removes them. The more common way to write the same thing is to keep the rows you want: df[df["team"] != "RCB"].
Example — del and pop
python
d = df.copy()
del d["sixes"]
balls = d.pop("balls")
print(balls.tolist(), d.columns.tolist())text
[564, 475, 457, 317] ['player', 'team', 'runs']del and pop change the DataFrame in place. pop also returns the removed column as a Series — handy for separating a target column (y = df.pop("price")) in machine learning.
Example — reorder columns
python
print(df[["team", "player", "sixes", "runs", "balls"]])
cols = ["runs"] + [c for c in df.columns if c != "runs"]
print(df[cols].columns.tolist())text
team player sixes runs balls
0 GT Shubman Gill 33 890 564
1 RCB Faf du Plessis 36 730 475
2 RCB Virat Kohli 16 639 457
3 KKR Rinku Singh 29 474 317
['runs', 'player', 'team', 'balls', 'sixes']How it works: selecting a list of columns returns them in the list's order. To move one column to the front without typing all the others, build the list with a comprehension. Other options: df.reindex(columns=[...]) (unknown names become all-NaN columns instead of raising), df.sort_index(axis=1) (alphabetical), and df.loc[:, "team":"balls"] (a label range of columns).
Comparison
| Task | Method | Changes df in place? |
|---|---|---|
| Rename some columns | df.rename(columns={...}) | no (reassign) |
| Rename all columns | df.columns = [...] | yes |
| Remove columns | df.drop(columns=[...]) | no (reassign) |
| Remove rows | df.drop(index=[...]) or filter | no (reassign) |
| Remove one column | del df["c"] / df.pop("c") | yes (pop returns it) |
| Reorder columns | df[[...]] / df.reindex(columns=[...]) | no (reassign) |
Common mistakes
- ❌
df.rename(columns={"runs": "total"})and then usingdf["total"]→KeyError. ✅df = df.rename(...)— rename returns a new DataFrame. - ❌
df.drop("balls")→KeyError(looks for a row called "balls"). ✅df.drop(columns="balls"). - ❌
df.rename({"runs": "total"})withoutcolumns=. ✅ A bare dict renames the index by default; always saycolumns=. - ❌
df = df.drop(columns="x", inplace=True)→dfbecomesNone. ✅ Choose one:df = df.drop(columns="x"). - ❌ Expecting row labels to be renumbered after a drop. ✅ Use
df.reset_index(drop=True)(covered in the indexing chapter).
Interview tip
Q: How do you drop a column in pandas, and what's the difference between drop, del and pop?
A: df.drop(columns=["c"]) returns a new DataFrame without the column (the original is unchanged unless reassigned). del df["c"] removes it in place and returns nothing. df.pop("c") removes it in place and returns the removed column as a Series.
Key points to remember
- df.rename(columns={'old': 'new'}) renames only the listed columns and returns a new DataFrame.
- Assigning df.columns = [...] replaces all names; the list length must match.
- Clean names fast with df.columns.str.strip().str.lower().str.replace(' ', '_').
- df.drop(columns=[...]) removes columns; df.drop(index=[...]) removes rows by label.
- drop raises KeyError for unknown labels unless errors='ignore'.
- del df['c'] and df.pop('c') remove a column in place; pop also returns it.
- Reorder columns by selecting them in a new order: df[['c3', 'c1', 'c2']].
Try it yourself
Rename columns and clean names
drop, del and pop
Reorder columns
Practice: tidy a raw scorecard
Revision Flashcards
Tap a card to flip it and see the answer.
