Summarizing and aggregating
Summarizing means turning many rows into few: one per group, one per window of time, or one per row across columns. This chapter goes through the ways Polars (and Nanuq) do it.
Split, apply, and combine
A group-by splits the rows by the values of one or more columns, applies an aggregation to each group, and combines the results into a new frame.
GroupBy context
group_by alone computes nothing; it waits for an aggregation.
import nanuq
let fruit = readCsv("data/definitive-guide/fruit.csv")
let fruitGrouped = fruit.groupBy("is_round")
nbShow fruitGrouped.len()
| is_round | len |
|---|---|
| bool | u32 |
| false | 6 |
| true | 4 |
import polars as pl
fruit = pl.read_csv("data/definitive-guide/fruit.csv")
fruit_grouped = fruit.group_by("is_round", maintain_order=True)
fruit_grouped.len()| is_round | len |
|---|---|
| bool | u32 |
| false | 6 |
| true | 4 |
The rest of the chapter uses the Top 2000 of 2023, the yearly list of the 2000 most popular songs according to the listeners of the Dutch radio station NPO Radio 2. It comes as an Excel file whose first row is a title, so one row is skipped:
let top2000 = readExcel(
"data/definitive-guide/top2000-2023.xlsx", skipRows = 1
).setSorted("positie")
nbShow top2000.head()
| positie | titel | artiest | jaar |
|---|---|---|---|
| i64 | str | str | i64 |
| 1 | "Bohemian Rhapsody" | "Queen" | 1975 |
| 2 | "Roller Coaster" | "Danny Vera" | 2019 |
| 3 | "Hotel California" | "Eagles" | 1977 |
| 4 | "Piano Man" | "Billy Joel" | 1974 |
| 5 | "Fix You" | "Coldplay" | 2005 |
top2000 = pl.read_excel(
"data/definitive-guide/top2000-2023.xlsx", read_options={"skip_rows": 1}
).set_sorted("positie")
top2000.head()| positie | titel | artiest | jaar |
|---|---|---|---|
| i64 | str | str | i64 |
| 1 | "Bohemian Rhapsody" | "Queen" | 1975 |
| 2 | "Roller Coaster" | "Danny Vera" | 2019 |
| 3 | "Hotel California" | "Eagles" | 1977 |
| 4 | "Piano Man" | "Billy Joel" | 1974 |
| 5 | "Fix You" | "Coldplay" | 2005 |
Without an aggregation, a column becomes a list per group: all the songs of each year, as "artist - title".
nbShow top2000.groupBy("jaar")
.agg(
concatStr([col.artiest, lit(" - "), col.titel]).alias("songs"))
.sort("jaar", descending = true)
| jaar | songs |
|---|---|
| i64 | list[str] |
| 2022 | ["Son Mieux - Multicolor", "Bankzitters - Je Blik Richting Mij", … "Måneskin - THE LONELIEST"] |
| 2021 | ["Goldband - Noodgeval", "Bankzitters - Stapelgek", … "Olivia Rodrigo - Drivers License"] |
| 2020 | ["DI-RECT - Soldier On", "Miss Montreal - Door De Wind", … "Dua Lipa ft. DaBaby - Levitating"] |
| 2019 | ["Danny Vera - Roller Coaster", "Floor Jansen & Henk Poort - Phantom Of The Opera", … "Tino Martin - Zij Weet Het"] |
| 2018 | ["Lady Gaga & Bradley Cooper - Shallow", "White Lies - Time To Give", … "Calvin Harris & Dua Lipa - One Kiss"] |
| … | … |
| 1960 | ["Etta James - At Last", "Shadows - Apache"] |
| 1959 | ["Jacques Brel - Ne Me Quitte Pas", "Elvis Presley - Hound Dog"] |
| 1958 | ["Chuck Berry - Johnny B. Goode", "Ella Fitzgerald & Louis Armstrong - Summertime"] |
| 1957 | ["Johnny Cash - I Walk The Line", "Elvis Presley - Jailhouse Rock", … "Fats Domino - Blueberry Hill"] |
| 1956 | ["Elvis Presley - Love Me Tender", "Elvis Presley - Blue Suede Shoes"] |
(
top2000.group_by("jaar")
.agg(
songs=pl.concat_str(
pl.col("artiest"), pl.lit(" - "), pl.col("titel")
),
)
.sort("jaar", descending=True)
)| jaar | songs |
|---|---|
| i64 | list[str] |
| 2022 | ["Son Mieux - Multicolor", "Bankzitters - Je Blik Richting Mij", … "Måneskin - THE LONELIEST"] |
| 2021 | ["Goldband - Noodgeval", "Bankzitters - Stapelgek", … "Olivia Rodrigo - Drivers License"] |
| 2020 | ["DI-RECT - Soldier On", "Miss Montreal - Door De Wind", … "Dua Lipa ft. DaBaby - Levitating"] |
| 2019 | ["Danny Vera - Roller Coaster", "Floor Jansen & Henk Poort - Phantom Of The Opera", … "Tino Martin - Zij Weet Het"] |
| 2018 | ["Lady Gaga & Bradley Cooper - Shallow", "White Lies - Time To Give", … "Calvin Harris & Dua Lipa - One Kiss"] |
| … | … |
| 1960 | ["Etta James - At Last", "Shadows - Apache"] |
| 1959 | ["Jacques Brel - Ne Me Quitte Pas", "Elvis Presley - Hound Dog"] |
| 1958 | ["Chuck Berry - Johnny B. Goode", "Ella Fitzgerald & Louis Armstrong - Summertime"] |
| 1957 | ["Johnny Cash - I Walk The Line", "Elvis Presley - Jailhouse Rock", … "Fats Domino - Blueberry Hill"] |
| 1956 | ["Elvis Presley - Love Me Tender", "Elvis Presley - Blue Suede Shoes"] |
The descriptives
head and tail keep the first and last rows of each group. Since the list is sorted by
position, these are the best and worst ranked songs of each year:
nbShow top2000.groupBy("jaar")
.head(3)
.sort("jaar", descending = true, maintainOrder = true)
.head(9)
| jaar | positie | titel | artiest |
|---|---|---|---|
| i64 | i64 | str | str |
| 2022 | 179 | "Multicolor" | "Son Mieux" |
| 2022 | 370 | "Je Blik Richting Mij" | "Bankzitters" |
| 2022 | 395 | "L'enfer" | "Stromae" |
| 2021 | 55 | "Noodgeval" | "Goldband" |
| 2021 | 149 | "Stapelgek" | "Bankzitters" |
| 2021 | 210 | "Dat Heb Jij Gedaan" | "Meau" |
| 2020 | 19 | "Soldier On" | "DI-RECT" |
| 2020 | 38 | "Door De Wind" | "Miss Montreal" |
| 2020 | 77 | "Impossible (Orchestral Version… | "Nothing But Thieves" |
(
top2000.group_by("jaar", maintain_order=True)
.head(3)
.sort("jaar", descending=True, maintain_order=True)
.head(9)
)| jaar | positie | titel | artiest |
|---|---|---|---|
| i64 | i64 | str | str |
| 2022 | 179 | "Multicolor" | "Son Mieux" |
| 2022 | 370 | "Je Blik Richting Mij" | "Bankzitters" |
| 2022 | 395 | "L'enfer" | "Stromae" |
| 2021 | 55 | "Noodgeval" | "Goldband" |
| 2021 | 149 | "Stapelgek" | "Bankzitters" |
| 2021 | 210 | "Dat Heb Jij Gedaan" | "Meau" |
| 2020 | 19 | "Soldier On" | "DI-RECT" |
| 2020 | 38 | "Door De Wind" | "Miss Montreal" |
| 2020 | 77 | "Impossible (Orchestral Version… | "Nothing But Thieves" |
nbShow top2000.groupBy("jaar")
.tail(3)
.sort("jaar", descending = true, maintainOrder = true)
.head(9)
| jaar | positie | titel | artiest |
|---|---|---|---|
| i64 | i64 | str | str |
| 2022 | 1391 | "De Diepte" | "S10" |
| 2022 | 1688 | "Zeit" | "Rammstein" |
| 2022 | 1716 | "THE LONELIEST" | "Måneskin" |
| 2021 | 1865 | "Bon Gepakt" | "Donnie & Rene Froger" |
| 2021 | 1978 | "Hold On" | "Armin van Buuren ft. Davina Mi… |
| 2021 | 2000 | "Drivers License" | "Olivia Rodrigo" |
| 2020 | 1824 | "Smoorverliefd" | "Snelle" |
| 2020 | 1879 | "The Business" | "Tiësto" |
| 2020 | 1902 | "Levitating" | "Dua Lipa ft. DaBaby" |
(
top2000.group_by("jaar", maintain_order=True)
.tail(3)
.sort("jaar", descending=True, maintain_order=True)
.head(9)
)| jaar | positie | titel | artiest |
|---|---|---|---|
| i64 | i64 | str | str |
| 2022 | 1391 | "De Diepte" | "S10" |
| 2022 | 1688 | "Zeit" | "Rammstein" |
| 2022 | 1716 | "THE LONELIEST" | "Måneskin" |
| 2021 | 1865 | "Bon Gepakt" | "Donnie & Rene Froger" |
| 2021 | 1978 | "Hold On" | "Armin van Buuren ft. Davina Mi… |
| 2021 | 2000 | "Drivers License" | "Olivia Rodrigo" |
| 2020 | 1824 | "Smoorverliefd" | "Snelle" |
| 2020 | 1879 | "The Business" | "Tiësto" |
| 2020 | 1902 | "Levitating" | "Dua Lipa ft. DaBaby" |
And the artists with the most songs in the list:
nbShow top2000.groupBy("artiest").len().sort(["len", "artiest"], descending = [true, false]).head(10)
| artiest | len |
|---|---|
| str | u32 |
| "Queen" | 34 |
| "The Beatles" | 31 |
| "ABBA" | 25 |
| "Bruce Springsteen" | 22 |
| "The Rolling Stones" | 22 |
| "Coldplay" | 20 |
| "Fleetwood Mac" | 20 |
| "Michael Jackson" | 20 |
| "David Bowie" | 18 |
| "U2" | 18 |
top2000.group_by("artiest").len().sort("len", "artiest", descending=[True, False]).head(10)| artiest | len |
|---|---|
| str | u32 |
| "Queen" | 34 |
| "The Beatles" | 31 |
| "ABBA" | 25 |
| "Bruce Springsteen" | 22 |
| "The Rolling Stones" | 22 |
| "Coldplay" | 20 |
| "Fleetwood Mac" | 20 |
| "Michael Jackson" | 20 |
| "David Bowie" | 18 |
| "U2" | 18 |
Row-wise aggregations
A fold walks over columns, carrying an accumulator from one to the next:
let foldExample = newDataFrame:
col1: [2]
col2: [3]
col3: [4]
nbShow foldExample.withColumns(
fold(
acc = lit(0),
f = proc (acc, x: Series): Series = acc + x,
exprs = col("*")).alias("sum"))
| col1 | col2 | col3 | sum |
|---|---|---|---|
| i64 | i64 | i64 | i32 |
| 2 | 3 | 4 | 9 |
fold_example = pl.DataFrame({"col1": [2], "col2": [3], "col3": [4]})
fold_example.with_columns(
sum=pl.fold(
acc=pl.lit(0),
function=lambda acc, x: acc + x,
exprs=pl.col("*"),
)
)| col1 | col2 | col3 | sum |
|---|---|---|---|
| i64 | i64 | i64 | i32 |
| 2 | 3 | 4 | 9 |
The columns to fold can be any expressions, here each product weighted:
import std/[sugar, tables]
let products = newDataFrame:
product_A: [10, 20, 30]
product_B: [20, 30, 40]
product_C: [30, 40, 50]
let weights = {"product_A": 0.5, "product_B": 1.5, "product_C": 2.0}.toOrderedTable
let weightedExprs = sugar.collect:
for product, weight in weights:
(col(product) * weight).alias(product)
let productsWithWeightedSum = products.withColumns(
fold(
acc = lit(0),
f = proc (acc, x: Series): Series = acc + x,
exprs = weightedExprs).alias("weighted_sum"))
nbShow productsWithWeightedSum
| product_A | product_B | product_C | weighted_sum |
|---|---|---|---|
| i64 | i64 | i64 | i32 |
| 10 | 20 | 30 | 95 |
| 20 | 30 | 40 | 135 |
| 30 | 40 | 50 | 175 |
products = pl.DataFrame(
{
"product_A": [10, 20, 30],
"product_B": [20, 30, 40],
"product_C": [30, 40, 50],
}
)
weights = {"product_A": 0.5, "product_B": 1.5, "product_C": 2.0}
weighted_exprs = [
(pl.col(product) * weight).alias(product)
for product, weight in weights.items()
]
products_with_weighted_sum = products.with_columns(
weighted_sum=pl.fold(
acc=pl.lit(0),
function=lambda acc, x: acc + x,
exprs=weighted_exprs,
)
)
products_with_weighted_sum| product_A | product_B | product_C | weighted_sum |
|---|---|---|---|
| i64 | i64 | i64 | i32 |
| 10 | 20 | 30 | 95 |
| 20 | 30 | 40 | 135 |
| 30 | 40 | 50 | 175 |
Window functions in selection context
over ranks each song within its year, and keeps all rows. The book then shows ten
random rows:
nbShow top2000.select(
col.jaar,
col.artiest,
col.titel,
col.positie,
col.positie.rank.over("jaar").alias("year_rank"),
).sample(10, seed = 42)
| jaar | artiest | titel | positie | year_rank |
|---|---|---|---|---|
| i64 | str | str | i64 | f64 |
| 1985 | "Paul McCartney & Frog Chorus" | "We All Stand Together" | 1622 | 45.0 |
| 1977 | "ABBA" | "Take A Chance On Me" | 636 | 23.0 |
| 1970 | "Carpenters" | "(They Long To Be) Close To You" | 1961 | 33.0 |
| 2021 | "Taylor Swift" | "Willow" | 1399 | 38.0 |
| 1985 | "Chris Rea" | "Josephine" | 1584 | 42.0 |
| 1999 | "Gé Reinders" | "Blaosmuziek" | 1174 | 14.0 |
| 1990 | "Frank Boeijen Groep" | "Zeg Me Dat Het Niet Zo Is" | 251 | 5.0 |
| 2008 | "Metallica" | "The Unforgiven III" | 1210 | 11.0 |
| 1991 | "Chris Isaak" | "Wicked Game" | 416 | 19.0 |
| 1994 | "Van Dik Hout" | "Meer Dan Een Ander" | 1867 | 30.0 |
top2000.select(
"jaar",
"artiest",
"titel",
"positie",
year_rank=pl.col("positie").rank().over("jaar"),
).sample(10, seed=42)| jaar | artiest | titel | positie | year_rank |
|---|---|---|---|---|
| i64 | str | str | i64 | f64 |
| 1985 | "Paul McCartney & Frog Chorus" | "We All Stand Together" | 1622 | 45.0 |
| 1977 | "ABBA" | "Take A Chance On Me" | 636 | 23.0 |
| 1970 | "Carpenters" | "(They Long To Be) Close To You" | 1961 | 33.0 |
| 2021 | "Taylor Swift" | "Willow" | 1399 | 38.0 |
| 1985 | "Chris Rea" | "Josephine" | 1584 | 42.0 |
| 1999 | "Gé Reinders" | "Blaosmuziek" | 1174 | 14.0 |
| 1990 | "Frank Boeijen Groep" | "Zeg Me Dat Het Niet Zo Is" | 251 | 5.0 |
| 2008 | "Metallica" | "The Unforgiven III" | 1210 | 11.0 |
| 1991 | "Chris Isaak" | "Wicked Game" | 416 | 19.0 |
| 1994 | "Van Dik Hout" | "Meer Dan Een Ander" | 1867 | 30.0 |
Dynamic grouping
Grouping by windows of time (group_by_dynamic) is covered in the user guide chapter
Time series: grouping.
Rolling aggregations
Two stores, sales every other weekday in April 2024:
let dates = select(
dateRange(date(2024, 4, 1), date(2024, 4, 26), "2d").alias("date"))
.filter(col.date.dt.weekday < 6)
let datesRepeated = concat([dates, dates]).sort("date")
var stores: seq[string]
for i in 0 ..< dates.height: stores.add ["Store A", "Store B"]
let smallSalesDf = datesRepeated.hstack([
series("store", stores),
series("sales", [
200, 150, 220, 160, 250, 180, 270, 190, 280, 210,
210, 170, 220, 180, 240, 190, 250, 200, 260, 210])])
.setSorted("date")
.setSorted("store")
nbShow smallSalesDf
| date | store | sales |
|---|---|---|
| date | str | i64 |
| 2024-04-01 | "Store A" | 200 |
| 2024-04-01 | "Store B" | 150 |
| 2024-04-03 | "Store A" | 220 |
| 2024-04-03 | "Store B" | 160 |
| 2024-04-05 | "Store A" | 250 |
| … | … | … |
| 2024-04-19 | "Store B" | 190 |
| 2024-04-23 | "Store A" | 250 |
| 2024-04-23 | "Store B" | 200 |
| 2024-04-25 | "Store A" | 260 |
| 2024-04-25 | "Store B" | 210 |
from datetime import date
dates = pl.date_range(
start=date(2024, 4, 1),
end=date(2024, 4, 26),
interval="2d",
eager=True,
)
dates = dates.filter(dates.dt.weekday() < 6)
dates_repeated = pl.concat([dates, dates]).sort()
small_sales_df = (
pl.DataFrame(
{
"date": dates_repeated,
"store": ["Store A", "Store B"] * dates.len(),
"sales": [
200, 150, 220, 160, 250, 180, 270, 190, 280, 210,
210, 170, 220, 180, 240, 190, 250, 200, 260, 210,
],
}
)
.set_sorted("date")
.set_sorted("store")
)
small_sales_df| date | store | sales |
|---|---|---|
| date | str | i64 |
| 2024-04-01 | "Store A" | 200 |
| 2024-04-01 | "Store B" | 150 |
| 2024-04-03 | "Store A" | 220 |
| 2024-04-03 | "Store B" | 160 |
| 2024-04-05 | "Store A" | 250 |
| … | … | … |
| 2024-04-19 | "Store B" | 190 |
| 2024-04-23 | "Store A" | 250 |
| 2024-04-23 | "Store B" | 200 |
| 2024-04-25 | "Store A" | 260 |
| 2024-04-25 | "Store B" | 210 |
A rolling window of 7 days per store sums the sales of the last week at every date; a join puts the result next to each day's sales:
let result = smallSalesDf.rolling(
indexColumn = "date",
period = "7d",
groupBy = "store",
).agg(
col.sales.sum.alias("sum_of_last_7_days_sales"))
let finalDf = smallSalesDf.join(result, on = ["date", "store"])
nbShow finalDf
| date | store | sales | sum_of_last_7_days_sales |
|---|---|---|---|
| date | str | i64 | i64 |
| 2024-04-01 | "Store A" | 200 | 200 |
| 2024-04-03 | "Store A" | 220 | 420 |
| 2024-04-05 | "Store A" | 250 | 670 |
| 2024-04-09 | "Store A" | 270 | 740 |
| 2024-04-11 | "Store A" | 280 | 800 |
| … | … | … | … |
| 2024-04-15 | "Store B" | 170 | 570 |
| 2024-04-17 | "Store B" | 180 | 560 |
| 2024-04-19 | "Store B" | 190 | 540 |
| 2024-04-23 | "Store B" | 200 | 570 |
| 2024-04-25 | "Store B" | 210 | 600 |
result = small_sales_df.rolling(
index_column="date",
period="7d",
group_by="store",
).agg(
sum_of_last_7_days_sales=pl.sum("sales")
)
final_df = small_sales_df.join(result, on=["date", "store"])
final_df| date | store | sales | sum_of_last_7_days_sales |
|---|---|---|---|
| date | str | i64 | i64 |
| 2024-04-01 | "Store A" | 200 | 200 |
| 2024-04-03 | "Store A" | 220 | 420 |
| 2024-04-05 | "Store A" | 250 | 670 |
| 2024-04-09 | "Store A" | 270 | 740 |
| 2024-04-11 | "Store A" | 280 | 800 |
| … | … | … | … |
| 2024-04-15 | "Store B" | 170 | 570 |
| 2024-04-17 | "Store B" | 180 | 560 |
| 2024-04-19 | "Store B" | 190 | 540 |
| 2024-04-23 | "Store B" | 200 | 570 |
| 2024-04-25 | "Store B" | 210 | 600 |
Upsampling
Upsampling adds the missing days, with nulls:
let upsampledSmallSalesDf = smallSalesDf.upsample(
timeColumn = "date", every = "1d", groupBy = "store", maintainOrder = true)
nbShow upsampledSmallSalesDf
| date | store | sales |
|---|---|---|
| date | str | i64 |
| 2024-04-01 | "Store A" | 200 |
| 2024-04-01 | "Store B" | 150 |
| 2024-04-03 | "Store A" | 220 |
| 2024-04-03 | "Store B" | 160 |
| 2024-04-05 | "Store A" | 250 |
| … | … | … |
| 2024-04-19 | "Store B" | 190 |
| 2024-04-23 | "Store A" | 250 |
| 2024-04-23 | "Store B" | 200 |
| 2024-04-25 | "Store A" | 260 |
| 2024-04-25 | "Store B" | 210 |
upsampled_small_sales_df = small_sales_df.upsample(
time_column="date", every="1d", group_by="store", maintain_order=True
)
upsampled_small_sales_df| date | store | sales |
|---|---|---|
| date | str | i64 |
| 2024-04-01 | "Store A" | 200 |
| 2024-04-01 | "Store B" | 150 |
| 2024-04-03 | "Store A" | 220 |
| 2024-04-03 | "Store B" | 160 |
| 2024-04-05 | "Store A" | 250 |
| … | … | … |
| 2024-04-19 | "Store B" | 190 |
| 2024-04-23 | "Store A" | 250 |
| 2024-04-23 | "Store B" | 200 |
| 2024-04-25 | "Store A" | 260 |
| 2024-04-25 | "Store B" | 210 |
which can then be filled: the store name forward, the sales by linear interpolation.
nbShow upsampledSmallSalesDf.select(
col.date, col.store.forwardFill, col.sales.interpolate)
| date | store | sales |
|---|---|---|
| date | str | f64 |
| 2024-04-01 | "Store A" | 200.0 |
| 2024-04-01 | "Store B" | 150.0 |
| 2024-04-03 | "Store A" | 220.0 |
| 2024-04-03 | "Store B" | 160.0 |
| 2024-04-05 | "Store A" | 250.0 |
| … | … | … |
| 2024-04-19 | "Store B" | 190.0 |
| 2024-04-23 | "Store A" | 250.0 |
| 2024-04-23 | "Store B" | 200.0 |
| 2024-04-25 | "Store A" | 260.0 |
| 2024-04-25 | "Store B" | 210.0 |
upsampled_small_sales_df.select(
"date", pl.col("store").forward_fill(), pl.col("sales").interpolate()
)| date | store | sales |
|---|---|---|
| date | str | f64 |
| 2024-04-01 | "Store A" | 200.0 |
| 2024-04-01 | "Store B" | 150.0 |
| 2024-04-03 | "Store A" | 220.0 |
| 2024-04-03 | "Store B" | 160.0 |
| 2024-04-05 | "Store A" | 250.0 |
| … | … | … |
| 2024-04-19 | "Store B" | 190.0 |
| 2024-04-23 | "Store A" | 250.0 |
| 2024-04-23 | "Store B" | 200.0 |
| 2024-04-25 | "Store A" | 260.0 |
| 2024-04-25 | "Store B" | 210.0 |
import nanuqbook
bookInit()
nbText: "# Summarizing and aggregating"
attribution definitiveGuide(13, "Summarizing and Aggregating",
"Data is read from `data/definitive-guide/`. Left out: the examples on `sales.csv` " &
"(15 MB, origin not stated), which show the same group-by methods on another table. " &
"Group-bys get `maintain_order=True` on the Python side where the order shows.")
nbText: """
Summarizing means turning many rows into few: one per group, one per window of time, or
one per row across columns. This chapter goes through the ways Polars (and Nanuq) do it.
## Split, apply, and combine
A group-by *splits* the rows by the values of one or more columns, *applies* an
aggregation to each group, and *combines* the results into a new frame.
## GroupBy context
`group_by` alone computes nothing; it waits for an aggregation.
"""
tabs """
import polars as pl
fruit = pl.read_csv("data/definitive-guide/fruit.csv")
fruit_grouped = fruit.group_by("is_round", maintain_order=True)
fruit_grouped.len()
""":
nbCode:
import nanuq
let fruit = readCsv("data/definitive-guide/fruit.csv")
let fruitGrouped = fruit.groupBy("is_round")
nbShow fruitGrouped.len()
nbText: """
The rest of the chapter uses the Top 2000 of 2023, the yearly list of the 2000 most
popular songs according to the listeners of the Dutch radio station NPO Radio 2. It comes
as an Excel file whose first row is a title, so one row is skipped:
"""
tabs """
top2000 = pl.read_excel(
"data/definitive-guide/top2000-2023.xlsx", read_options={"skip_rows": 1}
).set_sorted("positie")
top2000.head()
""":
nbCode:
let top2000 = readExcel(
"data/definitive-guide/top2000-2023.xlsx", skipRows = 1
).setSorted("positie")
nbShow top2000.head()
nanuq """
Python passes the options of its Excel engine as a dictionary (`read_options`); Nanuq's
`readExcel` has them as parameters. Both read the file with calamine.
"""
nbText: """
Without an aggregation, a column becomes a list per group: all the songs of each year,
as "artist - title".
"""
tabs """
(
top2000.group_by("jaar")
.agg(
songs=pl.concat_str(
pl.col("artiest"), pl.lit(" - "), pl.col("titel")
),
)
.sort("jaar", descending=True)
)
""":
nbCode:
nbShow top2000.groupBy("jaar")
.agg(
concatStr([col.artiest, lit(" - "), col.titel]).alias("songs"))
.sort("jaar", descending = true)
nbText: """
### The descriptives
`head` and `tail` keep the first and last rows of each group. Since the list is sorted by
position, these are the best and worst ranked songs of each year:
"""
tabs """
(
top2000.group_by("jaar", maintain_order=True)
.head(3)
.sort("jaar", descending=True, maintain_order=True)
.head(9)
)
""":
nbCode:
nbShow top2000.groupBy("jaar")
.head(3)
.sort("jaar", descending = true, maintainOrder = true)
.head(9)
tabs """
(
top2000.group_by("jaar", maintain_order=True)
.tail(3)
.sort("jaar", descending=True, maintain_order=True)
.head(9)
)
""":
nbCode:
nbShow top2000.groupBy("jaar")
.tail(3)
.sort("jaar", descending = true, maintainOrder = true)
.head(9)
nanuq """
Both tabs keep the order within a year in the final sort (`maintain_order=True`), so the
three songs of a year stay in list order.
"""
nbText: """
And the artists with the most songs in the list:
"""
tabs """
top2000.group_by("artiest").len().sort("len", "artiest", descending=[True, False]).head(10)
""":
nbCode:
nbShow top2000.groupBy("artiest").len().sort(["len", "artiest"], descending = [true, false]).head(10)
nanuq """
Ties on the count are broken by name in both tabs, so that the tenth place is the same.
The book goes on with `max`, `sum`, `n_unique`, `mean` and `quantile` on a group-by of a
sales table; Nanuq has the same shortcuts (`groupBy(…).max()`, …).
"""
nbText: """
## Row-wise aggregations
A fold walks over columns, carrying an accumulator from one to the next:
"""
tabs """
fold_example = pl.DataFrame({"col1": [2], "col2": [3], "col3": [4]})
fold_example.with_columns(
sum=pl.fold(
acc=pl.lit(0),
function=lambda acc, x: acc + x,
exprs=pl.col("*"),
)
)
""":
nbCode:
let foldExample = newDataFrame:
col1: [2]
col2: [3]
col3: [4]
nbShow foldExample.withColumns(
fold(
acc = lit(0),
f = proc (acc, x: Series): Series = acc + x,
exprs = col("*")).alias("sum"))
nbText: """
The columns to fold can be any expressions, here each product weighted:
"""
tabs """
products = pl.DataFrame(
{
"product_A": [10, 20, 30],
"product_B": [20, 30, 40],
"product_C": [30, 40, 50],
}
)
weights = {"product_A": 0.5, "product_B": 1.5, "product_C": 2.0}
weighted_exprs = [
(pl.col(product) * weight).alias(product)
for product, weight in weights.items()
]
products_with_weighted_sum = products.with_columns(
weighted_sum=pl.fold(
acc=pl.lit(0),
function=lambda acc, x: acc + x,
exprs=weighted_exprs,
)
)
products_with_weighted_sum
""":
nbCode:
import std/[sugar, tables]
let products = newDataFrame:
product_A: [10, 20, 30]
product_B: [20, 30, 40]
product_C: [30, 40, 50]
let weights = {"product_A": 0.5, "product_B": 1.5, "product_C": 2.0}.toOrderedTable
let weightedExprs = sugar.collect:
for product, weight in weights:
(col(product) * weight).alias(product)
let productsWithWeightedSum = products.withColumns(
fold(
acc = lit(0),
f = proc (acc, x: Series): Series = acc + x,
exprs = weightedExprs).alias("weighted_sum"))
nbShow productsWithWeightedSum
nbText: """
## Window functions in selection context
`over` ranks each song within its year, and keeps all rows. The book then shows ten
random rows:
"""
tabs """
top2000.select(
"jaar",
"artiest",
"titel",
"positie",
year_rank=pl.col("positie").rank().over("jaar"),
).sample(10, seed=42)
""":
nbCode:
nbShow top2000.select(
col.jaar,
col.artiest,
col.titel,
col.positie,
col.positie.rank.over("jaar").alias("year_rank"),
).sample(10, seed = 42)
nbText: """
## Dynamic grouping
Grouping by windows of time (`group_by_dynamic`) is covered in the user guide chapter
[Time series: grouping](../user-guide/time_series_grouping.html).
## Rolling aggregations
Two stores, sales every other weekday in April 2024:
"""
tabs """
from datetime import date
dates = pl.date_range(
start=date(2024, 4, 1),
end=date(2024, 4, 26),
interval="2d",
eager=True,
)
dates = dates.filter(dates.dt.weekday() < 6)
dates_repeated = pl.concat([dates, dates]).sort()
small_sales_df = (
pl.DataFrame(
{
"date": dates_repeated,
"store": ["Store A", "Store B"] * dates.len(),
"sales": [
200, 150, 220, 160, 250, 180, 270, 190, 280, 210,
210, 170, 220, 180, 240, 190, 250, 200, 260, 210,
],
}
)
.set_sorted("date")
.set_sorted("store")
)
small_sales_df
""":
nbCode:
let dates = select(
dateRange(date(2024, 4, 1), date(2024, 4, 26), "2d").alias("date"))
.filter(col.date.dt.weekday < 6)
let datesRepeated = concat([dates, dates]).sort("date")
var stores: seq[string]
for i in 0 ..< dates.height: stores.add ["Store A", "Store B"]
let smallSalesDf = datesRepeated.hstack([
series("store", stores),
series("sales", [
200, 150, 220, 160, 250, 180, 270, 190, 280, 210,
210, 170, 220, 180, 240, 190, 250, 200, 260, 210])])
.setSorted("date")
.setSorted("store")
nbShow smallSalesDf
nanuq """
Python builds the dates as a Series; in Nanuq a date range is an expression, so the dates
are a one-column frame, and the other columns are stacked next to it with `hstack`.
"""
nbText: """
A rolling window of 7 days per store sums the sales of the last week at every date; a join
puts the result next to each day's sales:
"""
tabs """
result = small_sales_df.rolling(
index_column="date",
period="7d",
group_by="store",
).agg(
sum_of_last_7_days_sales=pl.sum("sales")
)
final_df = small_sales_df.join(result, on=["date", "store"])
final_df
""":
nbCode:
let result = smallSalesDf.rolling(
indexColumn = "date",
period = "7d",
groupBy = "store",
).agg(
col.sales.sum.alias("sum_of_last_7_days_sales"))
let finalDf = smallSalesDf.join(result, on = ["date", "store"])
nbShow finalDf
nbText: """
## Upsampling
Upsampling adds the missing days, with nulls:
"""
tabs """
upsampled_small_sales_df = small_sales_df.upsample(
time_column="date", every="1d", group_by="store", maintain_order=True
)
upsampled_small_sales_df
""":
nbCode:
let upsampledSmallSalesDf = smallSalesDf.upsample(
timeColumn = "date", every = "1d", groupBy = "store", maintainOrder = true)
nbShow upsampledSmallSalesDf
nbText: """
which can then be filled: the store name forward, the sales by linear interpolation.
"""
tabs """
upsampled_small_sales_df.select(
"date", pl.col("store").forward_fill(), pl.col("sales").interpolate()
)
""":
nbCode:
nbShow upsampledSmallSalesDf.select(
col.date, col.store.forwardFill, col.sales.interpolate)
bookSave()
On GitHub: book/definitive-guide/summarizing_and_aggregating.nim