[practice]Pandas Fundamentals
Sorting & Adding Columns
# theory
sorting
Sort by one column:
df.sort_values("price") # Ascending (default)
df.sort_values("price", ascending=False) # Descending
Sort by multiple columns:
df.sort_values(["category", "price"], ascending=[True, False])
adding columns
Just assign to a new column name:
# Simple calculation
df["total"] = df["price"] * df["quantity"]
# Constant value
df["status"] = "active"
# Based on condition
df["expensive"] = df["price"] > 50
apply
For more complex transformations:
# Apply a function to each value
df["price_formatted"] = df["price"].apply(lambda x: f"${x:.2f}")
# Apply to each row (axis=1)
df["description"] = df.apply(
lambda row: f"{row['name']}: ${row['price']}", axis=1
)
modifying columns
# Update all values
df["price"] = df["price"] * 1.1 # 10% increase
# Update based on condition
df.loc[df["category"] == "Electronics", "price"] *= 0.9 # 10% discount# examples [3]
# example 01 · sorting examples
Various ways to sort data
1
2
3
4
5
6
7
8
9
🐍
# example 02 · calculated columns
Create new columns from existing data
1
2
3
4
5
6
7
8
9
10
🐍
# example 03 · using apply
Transform values with custom logic
1
2
3
4
5
6
7
8
9
10
🐍
# challenges [2]
# challenge 01/02todo
Sort the sales DataFrame by quantity in descending order and print the result.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
🐍
# challenge 02/02todo
Add a new column called 'revenue' to sales that is price * quantity. Print the product and revenue columns.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
🐍
# project
# project-challenge
thread: SF Permits Analysis · reward: 50 xp
# brief
The dashboard needs a boolean column to quickly identify active permits. Add an 'is_active' column that is True for permits with 'issued' or 'complete' status.
# task
Add Active Status Column
# 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
🐍