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)
shape: (1, 1)
absences
i64
75
nbShow mathStudents.select(col("student_id", "absences")).filter(
  col.absences == col.absences.max)
shape: (1, 2)
student_idabsences
i64i64
1027775

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"))
shape: (1, 3)
minmaxmean
i64i64f64
0755.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"))
shape: (395, 6)
student_idG1G2G3totalmean
i64i64i64i64i64f64
10001566175.666667
10002556165.333333
100037810258.333333
100041514154414.666667
1000561010268.666667
………………
10391999279.0
103921416164615.333333
103931087258.333333
103941112103311.0
10395899268.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"))
shape: (1, 3)
minmaxmean
i64i64f64
0323.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"))
shape: (2, 4)
subjectminmaxmean
stri64i64f64
"M"0755.708861
"P"0323.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"))
shape: (8, 2)
agepasses
i64list[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]

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"))
shape: (8, 2)
agepasses
i64list[i64]
18[14, 18, โ€ฆ 13]
17[13, 18, โ€ฆ 15]
15[15, 13, โ€ฆ 15]
16[15, 14, โ€ฆ 18]
19[13, 13, โ€ฆ 13]
22[]
20[]
21[]

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")
shape: (8, 4)
agepassespoor_attenderspercentage
i64u32u32f64
15153246.875
16113928.205128
1782927.586207
18113135.483871
1941040.0
20010.0
21000.0
22000.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"])
shape: (8, 5)
subjectreasonminmaxmean
strstri64i64f64
"M""course"0233.972414
"M""home"0757.146789
"M""other"0205.611111
"M""reputation"0566.647619
"P""course"0263.389474
"P""home"0304.456376
"P""other"0162.777778
"P""reputation"0323.811189
nbShow byReason.sort("reason", descending = true).sort("subject", maintainOrder = true)
shape: (8, 5)
subjectreasonminmaxmean
strstri64i64f64
"M""reputation"0566.647619
"M""other"0205.611111
"M""home"0757.146789
"M""course"0233.972414
"P""reputation"0323.811189
"P""other"0162.777778
"P""home"0304.456376
"P""course"0263.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
shape: (5, 4)
class_startclass_subjectabsenceslecturer_initials
datetime[ฮผs]stri64str
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"))
shape: (26, 3)
class_starttotal_absencesmean_absences
datetime[ฮผs]i64f64
2024-01-01 00:00:00103.333333
2024-01-08 00:00:00103.333333
2024-01-15 00:00:00113.666667
2024-01-22 00:00:00103.333333
2024-01-29 00:00:0041.333333
………
2024-05-27 00:00:00155.0
2024-06-03 00:00:00124.0
2024-06-10 00:00:00175.666667
2024-06-17 00:00:0062.0
2024-06-24 00:00:00144.666667
nbShow mathAttendance.groupByDynamic(
    indexColumn = "class_start",
    every = "1q",
    closed = ClosedWindow.Both,
    groupBy = "class_subject"
  ).agg(col.absences.sum)
shape: (6, 3)
class_subjectclass_startabsences
strdatetime[ฮผs]i64
"algebra"2024-01-01 00:00:0056
"algebra"2024-04-01 00:00:0044
"calculus"2024-01-01 00:00:0041
"calculus"2024-04-01 00:00:0039
"geometry"2024-01-01 00:00:0035
"geometry"2024-04-01 00:00:0040

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)
shape: (381, 6)
subjectschoolstudent_idreasonabsencesmean_absences
strstri64stri64f64
"M""GP"10001"course"64.104839
"M""GP"10003"other"106.518519
"M""GP"10006"reputation"106.72
"M""GP"10019"course"164.104839
"M""GP"10026"home"147.397959
………………
"P""MS"10645"course"42.627119
"P""MS"10646"course"42.627119
"P""MS"10647"course"62.627119
"P""MS"10648"course"62.627119
"P""MS"10649"course"42.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"))
shape: (4, 4)
subjectschoolmean_absencemean_failure
strstrf64f64
"M""GP"5.9656160.318052
"M""MS"3.760870.456522
"P""GP"4.215130.172577
"P""MS"2.6194690.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"]))
shape: (8, 6)
subjectreasonabsences_GPfailures_GPabsences_MSfailures_MS
strstrf64f64f64f64
"M""course"4.1048390.338713.1904760.52381
"M""other"6.5185190.3333332.8888890.222222
"M""home"7.3979590.3571434.9090910.636364
"M""reputation"6.720.255.20.2
"P""course"3.9281440.2455092.6271190.449153
"P""other"3.4074070.1851852.40.244444
"P""home"4.8695650.1304353.0588240.147059
"P""reputation"4.1666670.1052632.4137930.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()
Made with nimib and nimibook. Blocks marked "ran" were executed when this page was built.