BBampaa

Lessons › Python

Python lesson

Renaming and recoding

Same data, now readable: Store and Revenue columns, and full store names. A report built on it won't need a key to decode.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

.rename changes column names. .replace swaps values, using a dictionary of old: new:

df = df.rename(columns={"Shop": "Store", "Rev": "Revenue"})
df["Store"] = df["Store"].replace({"LAG": "Lagos", "ABJ": "Abuja", "KAN": "Kano"})
df

Output:

Ord Store Revenue
0 O501 Lagos 70
1 O502 Abuja 15
2 O503 Lagos 24
3 O504 Kano 40

Key points

.rename(columns={"Shop": "Store"})Old column name: new name. Others stay as they are.
.replace({"LAG": "Lagos"})Old value: new value, on a column.
A dictionaryCurly brackets of old: new pairs, separated by commas.
Save it backdf = df.rename(...) and df["Store"] = df["Store"].replace(...)

Rename columns with .rename(columns={old: new}), swap values with .replace({old: new}).

Practice

Try each one in your head first, then open the answer.

1. Build a line that renames Shop to Store.
df.rename(columns={"Shop": "Store"})
2. Build a line that turns the code LAG into Lagos in the Shop column.
df["Shop"].replace({"LAG": "Lagos"})
3. Rename the columns Ord, Shop and Rev to Order, Store and Revenue, and show the table.
df.rename(columns={"Ord": "Order", "Shop": "Store", "Rev": "Revenue"})
4. Swap the codes in Shop for full names: LAG is Lagos, ABJ is Abuja and KAN is Kano. Show the Shop column.
df["Shop"] = df["Shop"].replace({"LAG": "Lagos", "ABJ": "Abuja", "KAN": "Kano"})
df["Shop"]
5. Rename Rev to Revenue, then show the total revenue.
df = df.rename(columns={"Rev": "Revenue"})
df["Revenue"].sum()

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed