[practice]Grouping & Combining
Concat & Pivot
# theory
pd.concat()
Stack DataFrames vertically (add more rows):
combined = pd.concat([df1, df2, df3])
combined = pd.concat([df1, df2], ignore_index=True) # Fresh index
Stack horizontally (add more columns):
combined = pd.concat([df1, df2], axis=1)
pivot tables
Transform long data into wide format:
df.pivot_table(
values="amount", # What to aggregate
index="region", # Rows
columns="product", # Columns
aggfunc="sum" # How to aggregate
)
pivot vs pivot_table
- pivot(): Simple reshape, no aggregation (will error on duplicates)
- pivot_table(): Handles duplicates by aggregating
# Simple pivot (unique combinations only)
df.pivot(index="date", columns="product", values="sales")
# Pivot table (aggregates duplicates)
df.pivot_table(index="date", columns="product", values="sales", aggfunc="sum")
melt
Unpivot from wide to long format:
pd.melt(df, id_vars=["date"], value_vars=["A", "B", "C"])# examples [3]
# example 01 · concat dataframes
Stack DataFrames to combine rows
1
2
3
4
5
6
7
8
9
🐍
# example 02 · basic pivot table
Reshape data from long to wide format
1
2
3
4
5
6
7
8
9
🐍
# example 03 · pivot with multiple aggregations
Get several statistics in pivot format
1
2
3
4
5
6
7
🐍
# challenges [2]
# challenge 01/02todo
Create a pivot table showing average score by subject (as rows). Print the result.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
🐍
# challenge 02/02todo
Concat the first 3 rows and last 3 rows of students into a new DataFrame with a fresh index.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
🐍
# project
# project-challenge
thread: Survey Insights Report · reward: 50 xp
# brief
Create a salary comparison matrix for your report. Build a pivot table showing average salary with Country as rows and Education level as columns to identify compensation patterns.
# task
Salary Pivot by Country and Education
# 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
🐍