Grouping data
Students of two Portuguese schools, one row per student and course, with their grades in three
periods (G1, G2, G3, out of 20) and how many classes they missed (absences).
Aggregating a whole column
The most absences in the maths course, and who had them:
import nanuq
let mathStudents = readParquet("data/real-python/math.parquet")
nbShow mathStudents.select(col.absences.max)
| absences |
|---|
| i64 |
| 75 |
import polars as pl
math_students = pl.read_parquet("data/real-python/math.parquet")
(math_students.select(pl.col("absences").max()))| absences |
|---|
| i64 |
| 75 |
nbShow mathStudents.select(col("student_id", "absences")).filter(
col.absences == col.absences.max)
| student_id | absences |
|---|---|
| i64 | i64 |
| 10277 | 75 |
(
math_students.select(pl.col("student_id", "absences")).filter(
pl.col("absences") == pl.col("absences").max()
)
)| student_id | absences |
|---|---|
| i64 | i64 |
| 10277 | 75 |
Several aggregations at once, named with keyword arguments in Python and with alias in Nim:
nbShow mathStudents.select(
col.absences.min.alias("min"),
col.absences.max.alias("max"),
col.absences.mean.alias("mean"))
| min | max | mean |
|---|---|---|
| i64 | i64 | f64 |
| 0 | 75 | 5.708861 |
(
math_students.select(
min=pl.col("absences").min(),
max=pl.col("absences").max(),
mean=pl.col("absences").mean(),
)
)| min | max | mean |
|---|---|---|
| i64 | i64 | f64 |
| 0 | 75 | 5.708861 |
Aggregating across columns instead, row by row:
nbShow mathStudents.select(
col.student_id,
col.G1,
col.G2,
col.G3,
sumHorizontal(["G1", "G2", "G3"]).alias("total"),
meanHorizontal(["G1", "G2", "G3"]).alias("mean"))
| student_id | G1 | G2 | G3 | total | mean |
|---|---|---|---|---|---|
| i64 | i64 | i64 | i64 | i64 | f64 |
| 10001 | 5 | 6 | 6 | 17 | 5.666667 |
| 10002 | 5 | 5 | 6 | 16 | 5.333333 |
| 10003 | 7 | 8 | 10 | 25 | 8.333333 |
| 10004 | 15 | 14 | 15 | 44 | 14.666667 |
| 10005 | 6 | 10 | 10 | 26 | 8.666667 |
| … | … | … | … | … | … |
| 10391 | 9 | 9 | 9 | 27 | 9.0 |
| 10392 | 14 | 16 | 16 | 46 | 15.333333 |
| 10393 | 10 | 8 | 7 | 25 | 8.333333 |
| 10394 | 11 | 12 | 10 | 33 | 11.0 |
| 10395 | 8 | 9 | 9 | 26 | 8.666667 |
math_students.select(
"student_id",
"G1",
"G2",
"G3",
total=pl.sum_horizontal("G1", "G2", "G3"),
mean=pl.mean_horizontal("G1", "G2", "G3"),
)| student_id | G1 | G2 | G3 | total | mean |
|---|---|---|---|---|---|
| i64 | i64 | i64 | i64 | i64 | f64 |
| 10001 | 5 | 6 | 6 | 17 | 5.666667 |
| 10002 | 5 | 5 | 6 | 16 | 5.333333 |
| 10003 | 7 | 8 | 10 | 25 | 8.333333 |
| 10004 | 15 | 14 | 15 | 44 | 14.666667 |
| 10005 | 6 | 10 | 10 | 26 | 8.666667 |
| … | … | … | … | … | … |
| 10391 | 9 | 9 | 9 | 27 | 9.0 |
| 10392 | 14 | 16 | 16 | 46 | 15.333333 |
| 10393 | 10 | 8 | 7 | 25 | 8.333333 |
| 10394 | 11 | 12 | 10 | 33 | 11.0 |
| 10395 | 8 | 9 | 9 | 26 | 8.666667 |
Grouping by one column
The same statistics for the Portuguese course, and then for both courses at once, from the table that holds them both:
let portugueseStudents = readParquet("data/real-python/portuguese.parquet")
nbShow portugueseStudents.select(
col.absences.min.alias("min"),
col.absences.max.alias("max"),
col.absences.mean.alias("mean"))
| min | max | mean |
|---|---|---|
| i64 | i64 | f64 |
| 0 | 32 | 3.659476 |
portuguese_students = pl.read_parquet("data/real-python/portuguese.parquet")
(
portuguese_students.select(
min=pl.col("absences").min(),
max=pl.col("absences").max(),
mean=pl.col("absences").mean(),
)
)| min | max | mean |
|---|---|---|
| i64 | i64 | f64 |
| 0 | 32 | 3.659476 |
let allStudents = readParquet("data/real-python/course.parquet")
nbShow allStudents.groupBy("subject").agg(
col.absences.min.alias("min"),
col.absences.max.alias("max"),
col.absences.mean.alias("mean"))
| subject | min | max | mean |
|---|---|---|---|
| str | i64 | i64 | f64 |
| "M" | 0 | 75 | 5.708861 |
| "P" | 0 | 32 | 3.659476 |
all_students = pl.read_parquet("data/real-python/course.parquet")
(
all_students.group_by("subject").agg(
min=pl.col("absences").min(),
max=pl.col("absences").max(),
mean=pl.col("absences").mean(),
)
)| subject | min | max | mean |
|---|---|---|---|
| str | i64 | i64 | f64 |
| "M" | 0 | 75 | 5.708861 |
| "P" | 0 | 32 | 3.659476 |
An aggregation that is not one value: a list of the final grades of each age group,
nbShow mathStudents.groupBy("age").agg(
col.G3.alias("passes"))
| age | passes |
|---|---|
| i64 | list[i64] |
| 18 | [6, 0, โฆ 10] |
| 17 | [6, 6, โฆ 16] |
| 15 | [10, 15, โฆ 7] |
| 16 | [10, 15, โฆ 8] |
| 19 | [9, 0, โฆ 9] |
| 22 | [8] |
| 20 | [18, 15, 9] |
| 21 | [7] |
(
math_students.group_by("age").agg(
passes=pl.col("G3"),
)
)| age | passes |
|---|---|
| i64 | list[i64] |
| 18 | [6, 0, โฆ 10] |
| 15 | [10, 15, โฆ 7] |
| 17 | [6, 6, โฆ 16] |
| 21 | [7] |
| 19 | [9, 0, โฆ 9] |
| 20 | [18, 15, 9] |
| 22 | [8] |
| 16 | [10, 15, โฆ 8] |
and only the grades of good marks (13 or more) among students who missed more classes than average in their age group:
nbShow mathStudents.groupBy("age").agg(
col.G3.filter(
col.absences > col.absences.mean and col.G3 >= 13).alias("passes"))
| age | passes |
|---|---|
| i64 | list[i64] |
| 18 | [14, 18, โฆ 13] |
| 17 | [13, 18, โฆ 15] |
| 15 | [15, 13, โฆ 15] |
| 16 | [15, 14, โฆ 18] |
| 19 | [13, 13, โฆ 13] |
| 22 | [] |
| 20 | [] |
| 21 | [] |
(
math_students.group_by("age").agg(
passes=pl.col("G3").filter(
pl.col("absences") > pl.col("absences").mean(), pl.col("G3") >= 13
)
)
)| age | passes |
|---|---|
| i64 | list[i64] |
| 20 | [] |
| 18 | [14, 18, โฆ 13] |
| 19 | [13, 13, โฆ 13] |
| 21 | [] |
| 15 | [15, 13, โฆ 15] |
| 16 | [15, 14, โฆ 18] |
| 17 | [13, 18, โฆ 15] |
| 22 | [] |
Counting them instead, and the share they are of all the poor attenders:
nbShow mathStudents.groupBy("age")
.agg(
col.G3
.filter(col.absences > col.absences.mean and col.G3 >= 13)
.count.alias("passes"),
col.G3
.filter(col.absences > col.absences.mean)
.count.alias("poor_attenders"))
.select(
col("age", "passes", "poor_attenders"),
(col.passes / col.poor_attenders * 100).alias("percentage"))
.withColumns(col.percentage.replace(NaN, 0.0))
.sort("age")
| age | passes | poor_attenders | percentage |
|---|---|---|---|
| i64 | u32 | u32 | f64 |
| 15 | 15 | 32 | 46.875 |
| 16 | 11 | 39 | 28.205128 |
| 17 | 8 | 29 | 27.586207 |
| 18 | 11 | 31 | 35.483871 |
| 19 | 4 | 10 | 40.0 |
| 20 | 0 | 1 | 0.0 |
| 21 | 0 | 0 | 0.0 |
| 22 | 0 | 0 | 0.0 |
(
math_students.group_by("age")
.agg(
passes=pl.col("G3")
.filter(
pl.col("absences") > pl.col("absences").mean(), pl.col("G3") >= 13
)
.count(),
poor_attenders=pl.col("G3")
.filter(pl.col("absences") > pl.col("absences").mean())
.count(),
)
.select(
pl.col("age", "passes", "poor_attenders"),
percentage=pl.col("passes") / pl.col("poor_attenders") * 100,
)
.with_columns(pl.col("percentage").replace(float("NaN"), 0))
.sort("age")
)| age | passes | poor_attenders | percentage |
|---|---|---|---|
| i64 | u32 | u32 | f64 |
| 15 | 15 | 32 | 46.875 |
| 16 | 11 | 39 | 28.205128 |
| 17 | 8 | 29 | 27.586207 |
| 18 | 11 | 31 | 35.483871 |
| 19 | 4 | 10 | 40.0 |
| 20 | 0 | 1 | 0.0 |
| 21 | 0 | 0 | 0.0 |
| 22 | 0 | 0 | 0.0 |
Grouping by several columns
By course and by the reason the student gave for choosing the school, sorted in three ways:
let byReason = allStudents.groupBy("subject", "reason")
.agg(
col.absences.min.alias("min"),
col.absences.max.alias("max"),
col.absences.mean.alias("mean"))
nbShow byReason.sort(["subject", "reason"])
| subject | reason | min | max | mean |
|---|---|---|---|---|
| str | str | i64 | i64 | f64 |
| "M" | "course" | 0 | 23 | 3.972414 |
| "M" | "home" | 0 | 75 | 7.146789 |
| "M" | "other" | 0 | 20 | 5.611111 |
| "M" | "reputation" | 0 | 56 | 6.647619 |
| "P" | "course" | 0 | 26 | 3.389474 |
| "P" | "home" | 0 | 30 | 4.456376 |
| "P" | "other" | 0 | 16 | 2.777778 |
| "P" | "reputation" | 0 | 32 | 3.811189 |
(
all_students.group_by(["subject", "reason"])
.agg(
min=pl.col("absences").min(),
max=pl.col("absences").max(),
mean=pl.col("absences").mean(),
)
.sort("subject", "reason")
)| subject | reason | min | max | mean |
|---|---|---|---|---|
| str | str | i64 | i64 | f64 |
| "M" | "course" | 0 | 23 | 3.972414 |
| "M" | "home" | 0 | 75 | 7.146789 |
| "M" | "other" | 0 | 20 | 5.611111 |
| "M" | "reputation" | 0 | 56 | 6.647619 |
| "P" | "course" | 0 | 26 | 3.389474 |
| "P" | "home" | 0 | 30 | 4.456376 |
| "P" | "other" | 0 | 16 | 2.777778 |
| "P" | "reputation" | 0 | 32 | 3.811189 |
nbShow byReason.sort("reason", descending = true).sort("subject", maintainOrder = true)
| subject | reason | min | max | mean |
|---|---|---|---|---|
| str | str | i64 | i64 | f64 |
| "M" | "reputation" | 0 | 56 | 6.647619 |
| "M" | "other" | 0 | 20 | 5.611111 |
| "M" | "home" | 0 | 75 | 7.146789 |
| "M" | "course" | 0 | 23 | 3.972414 |
| "P" | "reputation" | 0 | 32 | 3.811189 |
| "P" | "other" | 0 | 16 | 2.777778 |
| "P" | "home" | 0 | 30 | 4.456376 |
| "P" | "course" | 0 | 26 | 3.389474 |
(
all_students.group_by(["subject", "reason"])
.agg(
min=pl.col("absences").min(),
max=pl.col("absences").max(),
mean=pl.col("absences").mean(),
)
.sort("reason", descending=True)
.sort("subject")
)| subject | reason | min | max | mean |
|---|---|---|---|---|
| str | str | i64 | i64 | f64 |
| "M" | "reputation" | 0 | 56 | 6.647619 |
| "M" | "other" | 0 | 20 | 5.611111 |
| "M" | "home" | 0 | 75 | 7.146789 |
| "M" | "course" | 0 | 23 | 3.972414 |
| "P" | "reputation" | 0 | 32 | 3.811189 |
| "P" | "other" | 0 | 16 | 2.777778 |
| "P" | "home" | 0 | 30 | 4.456376 |
| "P" | "course" | 0 | 26 | 3.389474 |
Grouping by time
math_classes.parquet has the absences at each class:
let mathAttendance = readParquet("data/real-python/math_classes.parquet")
nbShow mathAttendance.head
| class_start | class_subject | absences | lecturer_initials |
|---|---|---|---|
| datetime[ฮผs] | str | i64 | str |
| 2024-01-03 09:00:00 | "algebra" | 3 | "DH" |
| 2024-01-04 13:30:00 | "geometry" | 4 | "PS" |
| 2024-01-05 10:00:00 | "calculus" | 3 | "LM" |
| 2024-01-10 09:00:00 | "algebra" | 2 | "DH" |
| 2024-01-11 13:30:00 | "geometry" | 7 | "PS" |
math_attendance = pl.read_parquet("data/real-python/math_classes.parquet")
math_attendance.head()| class_start | class_subject | absences | lecturer_initials |
|---|---|---|---|
| datetime[ฮผs] | str | i64 | str |
| 2024-01-03 09:00:00 | "algebra" | 3 | "DH" |
| 2024-01-04 13:30:00 | "geometry" | 4 | "PS" |
| 2024-01-05 10:00:00 | "calculus" | 3 | "LM" |
| 2024-01-10 09:00:00 | "algebra" | 2 | "DH" |
| 2024-01-11 13:30:00 | "geometry" | 7 | "PS" |
Totals and means per week, and per quarter and subject:
nbShow mathAttendance.groupByDynamic(
indexColumn = "class_start", every = "1w", closed = ClosedWindow.Both
).agg(
col.absences.sum.alias("total_absences"),
col.absences.mean.alias("mean_absences"))
| class_start | total_absences | mean_absences |
|---|---|---|
| datetime[ฮผs] | i64 | f64 |
| 2024-01-01 00:00:00 | 10 | 3.333333 |
| 2024-01-08 00:00:00 | 10 | 3.333333 |
| 2024-01-15 00:00:00 | 11 | 3.666667 |
| 2024-01-22 00:00:00 | 10 | 3.333333 |
| 2024-01-29 00:00:00 | 4 | 1.333333 |
| … | … | … |
| 2024-05-27 00:00:00 | 15 | 5.0 |
| 2024-06-03 00:00:00 | 12 | 4.0 |
| 2024-06-10 00:00:00 | 17 | 5.666667 |
| 2024-06-17 00:00:00 | 6 | 2.0 |
| 2024-06-24 00:00:00 | 14 | 4.666667 |
(
math_attendance.group_by_dynamic(
index_column="class_start", every="1w", closed="both"
).agg(
total_absences=pl.col("absences").sum(),
mean_absences=pl.col("absences").mean(),
)
)| class_start | total_absences | mean_absences |
|---|---|---|
| datetime[ฮผs] | i64 | f64 |
| 2024-01-01 00:00:00 | 10 | 3.333333 |
| 2024-01-08 00:00:00 | 10 | 3.333333 |
| 2024-01-15 00:00:00 | 11 | 3.666667 |
| 2024-01-22 00:00:00 | 10 | 3.333333 |
| 2024-01-29 00:00:00 | 4 | 1.333333 |
| … | … | … |
| 2024-05-27 00:00:00 | 15 | 5.0 |
| 2024-06-03 00:00:00 | 12 | 4.0 |
| 2024-06-10 00:00:00 | 17 | 5.666667 |
| 2024-06-17 00:00:00 | 6 | 2.0 |
| 2024-06-24 00:00:00 | 14 | 4.666667 |
nbShow mathAttendance.groupByDynamic(
indexColumn = "class_start",
every = "1q",
closed = ClosedWindow.Both,
groupBy = "class_subject"
).agg(col.absences.sum)
| class_subject | class_start | absences |
|---|---|---|
| str | datetime[ฮผs] | i64 |
| "algebra" | 2024-01-01 00:00:00 | 56 |
| "algebra" | 2024-04-01 00:00:00 | 44 |
| "calculus" | 2024-01-01 00:00:00 | 41 |
| "calculus" | 2024-04-01 00:00:00 | 39 |
| "geometry" | 2024-01-01 00:00:00 | 35 |
| "geometry" | 2024-04-01 00:00:00 | 40 |
(
math_attendance.group_by_dynamic(
index_column="class_start",
every="1q",
closed="both",
group_by="class_subject",
).agg(pl.col("absences").sum())
)| class_subject | class_start | absences |
|---|---|---|
| str | datetime[ฮผs] | i64 |
| "algebra" | 2024-01-01 00:00:00 | 56 |
| "algebra" | 2024-04-01 00:00:00 | 44 |
| "calculus" | 2024-01-01 00:00:00 | 41 |
| "calculus" | 2024-04-01 00:00:00 | 39 |
| "geometry" | 2024-01-01 00:00:00 | 35 |
| "geometry" | 2024-04-01 00:00:00 | 40 |
Window functions
The mean absences of each student's group, next to their own, and then only the students above it:
nbShow allStudents.select(
col("subject", "school", "student_id", "reason", "absences"),
col.absences.mean.over("subject", "school", "reason").alias("mean_absences")
).filter(col.absences > col.mean_absences)
| subject | school | student_id | reason | absences | mean_absences |
|---|---|---|---|---|---|
| str | str | i64 | str | i64 | f64 |
| "M" | "GP" | 10001 | "course" | 6 | 4.104839 |
| "M" | "GP" | 10003 | "other" | 10 | 6.518519 |
| "M" | "GP" | 10006 | "reputation" | 10 | 6.72 |
| "M" | "GP" | 10019 | "course" | 16 | 4.104839 |
| "M" | "GP" | 10026 | "home" | 14 | 7.397959 |
| … | … | … | … | … | … |
| "P" | "MS" | 10645 | "course" | 4 | 2.627119 |
| "P" | "MS" | 10646 | "course" | 4 | 2.627119 |
| "P" | "MS" | 10647 | "course" | 6 | 2.627119 |
| "P" | "MS" | 10648 | "course" | 6 | 2.627119 |
| "P" | "MS" | 10649 | "course" | 4 | 2.627119 |
all_students.select(
pl.col("subject", "school", "student_id", "reason", "absences"),
mean_absences=(
pl.col("absences").mean().over("subject", "school", "reason")
),
).filter(pl.col("absences") > pl.col("mean_absences"))| subject | school | student_id | reason | absences | mean_absences |
|---|---|---|---|---|---|
| str | str | i64 | str | i64 | f64 |
| "M" | "GP" | 10001 | "course" | 6 | 4.104839 |
| "M" | "GP" | 10003 | "other" | 10 | 6.518519 |
| "M" | "GP" | 10006 | "reputation" | 10 | 6.72 |
| "M" | "GP" | 10019 | "course" | 16 | 4.104839 |
| "M" | "GP" | 10026 | "home" | 14 | 7.397959 |
| … | … | … | … | … | … |
| "P" | "MS" | 10645 | "course" | 4 | 2.627119 |
| "P" | "MS" | 10646 | "course" | 4 | 2.627119 |
| "P" | "MS" | 10647 | "course" | 6 | 2.627119 |
| "P" | "MS" | 10648 | "course" | 6 | 2.627119 |
| "P" | "MS" | 10649 | "course" | 4 | 2.627119 |
Pivot tables
Means by course and school, first as a group-by, then as a pivot with one column per school:
nbShow allStudents.groupBy("subject", "school").agg(
col.absences.mean.alias("mean_absence"),
col.failures.mean.alias("mean_failure"))
| subject | school | mean_absence | mean_failure |
|---|---|---|---|
| str | str | f64 | f64 |
| "M" | "GP" | 5.965616 | 0.318052 |
| "M" | "MS" | 3.76087 | 0.456522 |
| "P" | "GP" | 4.21513 | 0.172577 |
| "P" | "MS" | 2.619469 | 0.314159 |
(
all_students.group_by(["subject", "school"]).agg(
mean_absence=pl.col("absences").mean(),
mean_failure=pl.col("failures").mean(),
)
)| subject | school | mean_absence | mean_failure |
|---|---|---|---|
| str | str | f64 | f64 |
| "M" | "GP" | 5.965616 | 0.318052 |
| "M" | "MS" | 3.76087 | 0.456522 |
| "P" | "GP" | 4.21513 | 0.172577 |
| "P" | "MS" | 2.619469 | 0.314159 |
nbShow allStudents.pivot(
on = "school",
index = ["subject", "reason"],
values = ["absences", "failures"],
aggregateFunction = PivotAgg.Mean
).select(
col(["subject", "reason",
"absences_GP", "failures_GP", "absences_MS", "failures_MS"]))
| subject | reason | absences_GP | failures_GP | absences_MS | failures_MS |
|---|---|---|---|---|---|
| str | str | f64 | f64 | f64 | f64 |
| "M" | "course" | 4.104839 | 0.33871 | 3.190476 | 0.52381 |
| "M" | "other" | 6.518519 | 0.333333 | 2.888889 | 0.222222 |
| "M" | "home" | 7.397959 | 0.357143 | 4.909091 | 0.636364 |
| "M" | "reputation" | 6.72 | 0.25 | 5.2 | 0.2 |
| "P" | "course" | 3.928144 | 0.245509 | 2.627119 | 0.449153 |
| "P" | "other" | 3.407407 | 0.185185 | 2.4 | 0.244444 |
| "P" | "home" | 4.869565 | 0.130435 | 3.058824 | 0.147059 |
| "P" | "reputation" | 4.166667 | 0.105263 | 2.413793 | 0.068966 |
(
all_students.pivot(
on="school",
index=["subject", "reason"],
values=["absences", "failures"],
aggregate_function="mean",
).select(
pl.col(
"subject",
"reason",
"absences_GP",
"failures_GP",
"absences_MS",
"failures_MS",
),
)
)| subject | reason | absences_GP | failures_GP | absences_MS | failures_MS |
|---|---|---|---|---|---|
| str | str | f64 | f64 | f64 | f64 |
| "M" | "course" | 4.104839 | 0.33871 | 3.190476 | 0.52381 |
| "M" | "other" | 6.518519 | 0.333333 | 2.888889 | 0.222222 |
| "M" | "home" | 7.397959 | 0.357143 | 4.909091 | 0.636364 |
| "M" | "reputation" | 6.72 | 0.25 | 5.2 | 0.2 |
| "P" | "course" | 3.928144 | 0.245509 | 2.627119 | 0.449153 |
| "P" | "other" | 3.407407 | 0.185185 | 2.4 | 0.244444 |
| "P" | "home" | 4.869565 | 0.130435 | 3.058824 | 0.147059 |
| "P" | "reputation" | 4.166667 | 0.105263 | 2.413793 | 0.068966 |
import nanuqbook
bookInit()
nbText: "# Grouping data"
attribution realPython("How to Group Data Using Polars .group_by()", "polars-groupby",
"polars-groupby",
"The data is the UCI Student Performance dataset (Cortez and Silva, 2008, CC BY 4.0), " &
"as the tutorial's Parquet files: `data/real-python/math.parquet`, `portuguese.parquet` " &
"and `course.parquet` (both courses, with a `subject` column), plus `math_classes.parquet` " &
"(absences per class). Cells that repeat an earlier one are left out.")
nbText: """
Students of two Portuguese schools, one row per student and course, with their grades in three
periods (`G1`, `G2`, `G3`, out of 20) and how many classes they missed (`absences`).
## Aggregating a whole column
The most absences in the maths course, and who had them:
"""
tabs """
import polars as pl
math_students = pl.read_parquet("data/real-python/math.parquet")
(math_students.select(pl.col("absences").max()))
""":
nbCode:
import nanuq
let mathStudents = readParquet("data/real-python/math.parquet")
nbShow mathStudents.select(col.absences.max)
tabs """
(
math_students.select(pl.col("student_id", "absences")).filter(
pl.col("absences") == pl.col("absences").max()
)
)
""":
nbCode:
nbShow mathStudents.select(col("student_id", "absences")).filter(
col.absences == col.absences.max)
nbText: """
Several aggregations at once, named with keyword arguments in Python and with `alias` in Nim:
"""
tabs """
(
math_students.select(
min=pl.col("absences").min(),
max=pl.col("absences").max(),
mean=pl.col("absences").mean(),
)
)
""":
nbCode:
nbShow mathStudents.select(
col.absences.min.alias("min"),
col.absences.max.alias("max"),
col.absences.mean.alias("mean"))
nanuq """
Nim has keyword arguments too, but not an open set of them, so Nanuq names a new column with
`alias` (or `name.suffix` and the like).
"""
nbText: """
Aggregating across columns instead, row by row:
"""
tabs """
math_students.select(
"student_id",
"G1",
"G2",
"G3",
total=pl.sum_horizontal("G1", "G2", "G3"),
mean=pl.mean_horizontal("G1", "G2", "G3"),
)
""":
nbCode:
nbShow mathStudents.select(
col.student_id,
col.G1,
col.G2,
col.G3,
sumHorizontal(["G1", "G2", "G3"]).alias("total"),
meanHorizontal(["G1", "G2", "G3"]).alias("mean"))
nbText: """
## Grouping by one column
The same statistics for the Portuguese course, and then for both courses at once, from the
table that holds them both:
"""
tabs """
portuguese_students = pl.read_parquet("data/real-python/portuguese.parquet")
(
portuguese_students.select(
min=pl.col("absences").min(),
max=pl.col("absences").max(),
mean=pl.col("absences").mean(),
)
)
""":
nbCode:
let portugueseStudents = readParquet("data/real-python/portuguese.parquet")
nbShow portugueseStudents.select(
col.absences.min.alias("min"),
col.absences.max.alias("max"),
col.absences.mean.alias("mean"))
tabs """
all_students = pl.read_parquet("data/real-python/course.parquet")
(
all_students.group_by("subject").agg(
min=pl.col("absences").min(),
max=pl.col("absences").max(),
mean=pl.col("absences").mean(),
)
)
""":
nbCode:
let allStudents = readParquet("data/real-python/course.parquet")
nbShow allStudents.groupBy("subject").agg(
col.absences.min.alias("min"),
col.absences.max.alias("max"),
col.absences.mean.alias("mean"))
nbText: """
An aggregation that is not one value: a list of the final grades of each age group,
"""
tabs """
(
math_students.group_by("age").agg(
passes=pl.col("G3"),
)
)
""":
nbCode:
nbShow mathStudents.groupBy("age").agg(
col.G3.alias("passes"))
nbText: """
and only the grades of good marks (13 or more) among students who missed more classes than
average in their age group:
"""
tabs """
(
math_students.group_by("age").agg(
passes=pl.col("G3").filter(
pl.col("absences") > pl.col("absences").mean(), pl.col("G3") >= 13
)
)
)
""":
nbCode:
nbShow mathStudents.groupBy("age").agg(
col.G3.filter(
col.absences > col.absences.mean and col.G3 >= 13).alias("passes"))
nanuq """
Python's `Expr.filter` takes several predicates and joins them with *and*; Nanuq's takes one,
so the Nim tab joins them itself.
"""
nbText: """
Counting them instead, and the share they are of all the poor attenders:
"""
tabs """
(
math_students.group_by("age")
.agg(
passes=pl.col("G3")
.filter(
pl.col("absences") > pl.col("absences").mean(), pl.col("G3") >= 13
)
.count(),
poor_attenders=pl.col("G3")
.filter(pl.col("absences") > pl.col("absences").mean())
.count(),
)
.select(
pl.col("age", "passes", "poor_attenders"),
percentage=pl.col("passes") / pl.col("poor_attenders") * 100,
)
.with_columns(pl.col("percentage").replace(float("NaN"), 0))
.sort("age")
)
""":
nbCode:
nbShow mathStudents.groupBy("age")
.agg(
col.G3
.filter(col.absences > col.absences.mean and col.G3 >= 13)
.count.alias("passes"),
col.G3
.filter(col.absences > col.absences.mean)
.count.alias("poor_attenders"))
.select(
col("age", "passes", "poor_attenders"),
(col.passes / col.poor_attenders * 100).alias("percentage"))
.withColumns(col.percentage.replace(NaN, 0.0))
.sort("age")
nbText: """
## Grouping by several columns
By course and by the reason the student gave for choosing the school, sorted in three ways:
"""
tabs """
(
all_students.group_by(["subject", "reason"])
.agg(
min=pl.col("absences").min(),
max=pl.col("absences").max(),
mean=pl.col("absences").mean(),
)
.sort("subject", "reason")
)
""":
nbCode:
let byReason = allStudents.groupBy("subject", "reason")
.agg(
col.absences.min.alias("min"),
col.absences.max.alias("max"),
col.absences.mean.alias("mean"))
nbShow byReason.sort(["subject", "reason"])
tabs """
(
all_students.group_by(["subject", "reason"])
.agg(
min=pl.col("absences").min(),
max=pl.col("absences").max(),
mean=pl.col("absences").mean(),
)
.sort("reason", descending=True)
.sort("subject")
)
""":
nbCode:
nbShow byReason.sort("reason", descending = true).sort("subject", maintainOrder = true)
nanuq """
The tutorial also sorts by `subject` alone first, which leaves the order of the reasons to
chance; the port starts from the two-key sort. In the last cell, a second sort only keeps the
first one's order within each subject if it is stable: Python's `sort` does not promise that
unless asked (`maintain_order=True`), so the Nim tab asks with `maintainOrder = true`.
"""
nbText: """
## Grouping by time
`math_classes.parquet` has the absences at each class:
"""
tabs """
math_attendance = pl.read_parquet("data/real-python/math_classes.parquet")
math_attendance.head()
""":
nbCode:
let mathAttendance = readParquet("data/real-python/math_classes.parquet")
nbShow mathAttendance.head
nbText: """
Totals and means per week, and per quarter and subject:
"""
tabs """
(
math_attendance.group_by_dynamic(
index_column="class_start", every="1w", closed="both"
).agg(
total_absences=pl.col("absences").sum(),
mean_absences=pl.col("absences").mean(),
)
)
""":
nbCode:
nbShow mathAttendance.groupByDynamic(
indexColumn = "class_start", every = "1w", closed = ClosedWindow.Both
).agg(
col.absences.sum.alias("total_absences"),
col.absences.mean.alias("mean_absences"))
tabs """
(
math_attendance.group_by_dynamic(
index_column="class_start",
every="1q",
closed="both",
group_by="class_subject",
).agg(pl.col("absences").sum())
)
""":
nbCode:
nbShow mathAttendance.groupByDynamic(
indexColumn = "class_start",
every = "1q",
closed = ClosedWindow.Both,
groupBy = "class_subject"
).agg(col.absences.sum)
nbText: """
## Window functions
The mean absences of each student's group, next to their own, and then only the students above
it:
"""
tabs """
all_students.select(
pl.col("subject", "school", "student_id", "reason", "absences"),
mean_absences=(
pl.col("absences").mean().over("subject", "school", "reason")
),
).filter(pl.col("absences") > pl.col("mean_absences"))
""":
nbCode:
nbShow allStudents.select(
col("subject", "school", "student_id", "reason", "absences"),
col.absences.mean.over("subject", "school", "reason").alias("mean_absences")
).filter(col.absences > col.mean_absences)
nbText: """
## Pivot tables
Means by course and school, first as a group-by, then as a pivot with one column per school:
"""
tabs """
(
all_students.group_by(["subject", "school"]).agg(
mean_absence=pl.col("absences").mean(),
mean_failure=pl.col("failures").mean(),
)
)
""":
nbCode:
nbShow allStudents.groupBy("subject", "school").agg(
col.absences.mean.alias("mean_absence"),
col.failures.mean.alias("mean_failure"))
tabs """
(
all_students.pivot(
on="school",
index=["subject", "reason"],
values=["absences", "failures"],
aggregate_function="mean",
).select(
pl.col(
"subject",
"reason",
"absences_GP",
"failures_GP",
"absences_MS",
"failures_MS",
),
)
)
""":
nbCode:
nbShow allStudents.pivot(
on = "school",
index = ["subject", "reason"],
values = ["absences", "failures"],
aggregateFunction = PivotAgg.Mean
).select(
col(["subject", "reason",
"absences_GP", "failures_GP", "absences_MS", "failures_MS"]))
bookSave()
On GitHub: book/real-python/groupby.nim