PY-401 ยท Summarising and joining
apply and map
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
map replaces each value in a column using a dictionary or function, such as turning "D" into "Data". apply runs a function on every value of a column, or on every row with axis=1, for rules that built-in methods cannot express. Prefer plain vectorised maths like df["salary"] / 12 when it works, because it is much faster.
- Translate codes with map
- Label values with apply
- Combine columns per row with axis=1
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
import pandas as pdstaff = pd.DataFrame({"name": ["Asha", "Ben", "Chen"],"team": ["D", "W", "D"],"salary": [72000, 58000, 81000],})staff["team"] = staff["team"].map({"D": "Data", "W": "Web"})staff["band"] = staff["salary"].apply(lambda s: "Senior" if s >= 70000 else "Mid")staff["monthly"] = (staff["salary"] / 12).round()print(staff)print(staff.apply(lambda row: f"{row['name']} ({row['team']})", axis=1).tolist())
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
name team salary band monthly
0 Asha Data 72000 Senior 6000.0
1 Ben Web 58000 Mid 4833.0
2 Chen Data 81000 Senior 6750.0
['Asha (Data)', 'Ben (Web)', 'Chen (Data)'] ๐ฏ Add a column "grade" to marks: "Pass" when score is 50 or more, otherwise "Fail". Then map "subject" codes using names.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
marks["grade"] = marks["score"].apply(lambda s: "Pass" if s >= 50 else "Fail"); marks["subject"] = marks["subject"].map(names)
- The problemHR exports teams as single letters and wants salary bands on the report: Senior from 70,000, Mid below. No pandas method does exactly that, so you write the rule once and apply it.
- The Python idea
df["col"].map({"a": "Apple"})mapreplaces each value in a column using a dictionary or function, such as turning "D" into "Data". - In real lifeA logistics team maps country codes to regions with a dictionary, then applies a function that sets "express" or "standard" from both the weight and the destination of each parcel.
Start with a question
HR exports teams as single letters and wants salary bands on the report: Senior from 70,000, Mid below. No pandas method does exactly that, so you write the rule once and apply it.
Real reports need business rules: bands, categories, labels and flags. map and apply are how you add your own rules to a table.
Explain it like I'm 10
map is a translation card: every time you see "D", write "Data". apply is a helper who looks at each item and follows your rule, such as "if it costs more than 70, mark it Senior".
The technical explanation
df["team"].map({"D": "Data", "W": "Web"}) looks up each value in the dictionary.
df["salary"].apply(func) calls func with each value. A short lambda is common for one-line rules.
df.apply(func, axis=1) calls func with each whole row, so the function can read several columns: row["name"], row["team"].
apply runs Python code per value, which is slow on millions of rows. Use vectorised maths, np.where or pd.cut when they fit.
Syntax
df["col"].map({"a": "Apple"})
df["col"].apply(lambda x: ...)
df.apply(lambda row: ..., axis=1) Real-world scenario
A logistics team maps country codes to regions with a dictionary, then applies a function that sets "express" or "standard" from both the weight and the destination of each parcel.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: matplotlib basics โQuestions people ask
What is the difference between map and apply in pandas?
map works on a Series and is ideal for translating values with a dictionary. apply calls a function on each value of a Series, or on each row or column of a DataFrame with axis.
Why is pandas apply slow?
apply calls your Python function once per value or row, so it loses NumPy's compiled speed. Vectorised operations, np.where, np.select and pd.cut do the same jobs much faster on large tables.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner What is the difference between map and apply in pandas?
map works on a Series and is ideal for translating values with a dictionary. apply calls a function on each value of a Series, or on each row or column of a DataFrame with axis.
beginner Why is pandas apply slow?
apply calls your Python function once per value or row, so it loses NumPy's compiled speed. Vectorised operations, np.where, np.select and pd.cut do the same jobs much faster on large tables.
intermediate df["code"].map({"A": "Apple"}) turns "B" intoโฆ
NaN. Values missing from the dictionary become NaN.
intermediate What does apply(func) do on a column?
Calls func with each value. apply runs the function value by value.
Quick revision
Remember
- Translate codes with map
- Label values with apply
- Combine columns per row with axis=1
mapwith a dictionary turns values missing from the dictionary into NaN. Check with.isna().sum()after mapping, or add the missing keys.
Syntax
df["col"].map({"a": "Apple"})
df["col"].apply(lambda x: ...)
df.apply(lambda row: ..., axis=1) Official documentation
- pandas.Series.map (docs.python.org)
- pandas.DataFrame.apply (docs.python.org)