🎓 A1Learner
🔍
0 of 50 lessons completed

Changing Values with map and apply

map changes each value in a Series using a lookup. apply runs a small function on each value.

map with a dict lookup

Each category is swapped for its short code.

import pandas as pd

df = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug", "Pen"],
    "category": ["Drink", "Drink", "Home", "Office"],
    "units": [2, 1, 3, 5],
})
print(df["category"].map({"Drink": "D", "Home": "H", "Office": "O"}))

apply with a small function

The small function doubles each unit count.

import pandas as pd

df = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug", "Pen"],
    "category": ["Drink", "Drink", "Home", "Office"],
    "units": [2, 1, 3, 5],
})
print(df["units"].apply(lambda n: n * 2))

replace swaps named values

Only Tea and Coffee change. Mug and Pen stay as they are.

import pandas as pd

df = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug", "Pen"],
    "category": ["Drink", "Drink", "Home", "Office"],
    "units": [2, 1, 3, 5],
})
print(df["product"].replace({"Tea": "Green Tea", "Coffee": "Black Coffee"}))

Example

import io
import pandas as pd

SALES_CSV = """order_id,date,product,category,units,price,region
101,2026-01-05,Tea,Drink,2,4.50,North
102,2026-01-06,Coffee,Drink,1,6.00,South
103,2026-01-07,Mug,Home,3,12.00,East
104,2026-01-08,Notebook,Office,2,8.50,West
105,2026-01-09,Pen,Office,5,2.00,North
106,2026-01-12,Lamp,Home,1,24.00,South
107,2026-01-13,Tea,Drink,4,4.50,East
108,2026-01-14,Coffee,Drink,2,6.00,West
109,2026-01-15,Mug,Home,1,12.00,North
110,2026-01-16,Notebook,Office,3,8.50,South
111,2026-01-19,Pen,Office,2,2.00,East
112,2026-01-20,Lamp,Home,2,24.00,West"""

sales = pd.read_csv(io.StringIO(SALES_CSV))
sales["revenue"] = sales["units"] * sales["price"]
sales["code"] = sales["category"].map({"Drink": "D", "Home": "H", "Office": "O"})
print(sales[["product", "code", "revenue"]].head())
print(sales["revenue"].sum())

Key points

  • Use map with a dict to swap each value for its lookup.
  • Use apply with a small function to compute a new value from each old value.
  • Use replace with a dict to swap only the values the dict names.
  • map, apply, and replace each return a new Series.

In this example, the sales table is read from the CSV text. Revenue is units times price for each row, and map swaps each category for a short code. head shows the first five rows with the new columns, and the total revenue is 221.5.

Note

map turns a value with no lookup into NaN. A lookup dict must cover every value in the column.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which method changes every value in a Series through a lookup dict?