Lesson 18 of 23
โฎPrev Nextโฏ

PY-401 ยท Summarising and joining

apply and map

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

18of 23

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก 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.

    apply and map, running
    1. import pandas as pd
    2. staff = pd.DataFrame({
    3. "name": ["Asha", "Ben", "Chen"],
    4. "team": ["D", "W", "D"],
    5. "salary": [72000, 58000, 81000],
    6. })
    7. staff["team"] = staff["team"].map({"D": "Data", "W": "Web"})
    8. staff["band"] = staff["salary"].apply(lambda s: "Senior" if s >= 70000 else "Mid")
    9. staff["monthly"] = (staff["salary"] / 12).round()
    10. print(staff)
    11. print(staff.apply(lambda row: f"{row['name']} ({row['team']})", axis=1).tolist())
    Press โ–ถ to watch Python run this, one line at a time.
    1. 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.
    2. The Python ideadf["col"].map({"a": "Apple"})map replaces each value in a column using a dictionary or function, such as turning "D" into "Data".
    3. 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)

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    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.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. df["code"].map({"A": "Apple"}) turns "B" intoโ€ฆ
    2. 2. What does apply(func) do on a column?
    3. 3. How do you give a function a whole row?
    4. 4. Which is fastest for df["salary"] / 12?
    5. 5. When is apply the right tool?

    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
    • map with 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