pyodide: loading…

[practice]Functions & Apply

Apply & Map

# theory

Series.apply()

Apply a function to each value in a Series:

df["grade"] = df["score"].apply(lambda x: "A" if x >= 90 else "B")

Or with a named function:

def get_grade(score):
    if score >= 90: return "A"
    elif score >= 80: return "B"
    else: return "C"

df["grade"] = df["score"].apply(get_grade)

DataFrame.apply()

Apply function to rows or columns:

# Apply to each column (axis=0, default)
df.apply(lambda col: col.max())

# Apply to each row (axis=1)
df.apply(lambda row: row["price"] * row["qty"], axis=1)

Series.map()

Transform values using a dictionary or function:

# Using dictionary
df["grade_name"] = df["grade"].map({
    "A": "Excellent",
    "B": "Good",
    "C": "Average"
})

# Using function
df["score_doubled"] = df["score"].map(lambda x: x * 2)

apply vs map vs applymap

MethodUse Case
Series.apply()Function on each Series value
Series.map()Dict mapping or function on Series
DataFrame.apply()Function on rows or columns
DataFrame.map()Element-wise function on entire DataFrame

# examples [3]

# example 01 · Series.apply() examples

Transform individual values

1
2
3
4
5
6
7
8
9
10
11
12
13
14
🐍
Loading PythonSetting up pandas & numpy...
# example 02 · DataFrame.apply() with axis=1

Access multiple columns in each row

1
2
3
4
5
6
7
8
9
🐍
Loading PythonSetting up pandas & numpy...
# example 03 · using map() with dict

Translate values using a dictionary

1
2
3
4
5
6
7
8
9
10
11
12
13
🐍
Loading PythonSetting up pandas & numpy...

# challenges [2]

# challenge 01/02todo
Use apply() to create a 'passed' column that is True if score >= 70, False otherwise.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
🐍
Loading PythonSetting up pandas & numpy...
# challenge 02/02todo
Use map() with a dict to convert grades A→4, B→3, C→2. Print the result.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
🐍
Loading PythonSetting up pandas & numpy...

# project

# project-challenge

thread: Sales Performance Dashboard · reward: 50 xp

# brief

Sales operations wants to assign priority levels to customers based on their segment. Use map to add a Priority column where Enterprise=1, SMB=2, Consumer=3.

# task

Map Customer Priority Levels

# your code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
🐍
Loading PythonSetting up pandas & numpy...