Data transformation techniques

This chapter of the cookbook is about aggregating: over a whole column, per group, across columns, and over a window. Most of it uses Contoso, a made-up retail chain whose sales SQLBI generates for Power BI demos, and the last part the PokΓ©mon table.

Simple aggregations

How to do it...

import nanuq

var df = readCsv("data/polars-cookbook/contoso_sales.csv", tryParseDates = true)
nbShow df.head()
shape: (5, 20)
Order NumberLine NumberOrder DateDelivery DateCustomer NameCustomer GenderCustomer CountryCustomer AgeStore NameProduct NameColorBrandCategorySubcategoryQuantityUnit PriceNet PriceUnit CostCurrency CodeExchange Rate
i64i64datedatestrstrstri64strstrstrstrstrstri64f64f64f64strf64
28480612017-10-182017-10-20"Eric Kennedy""Male""United States"47"Online store""Contoso 512MB MP3 Player E51 S…"Silver""Contoso""Audio""MP4&MP3"711.69110.2885.958"USD"1.0
28550612017-10-252017-10-26"George Tooth""Male""Australia"30"Online store""Contoso 512MB MP3 Player E51 S…"Silver""Contoso""Audio""MP4&MP3"111.69111.6915.958"AUD"1.2967
31100222018-07-072018-07-12"Caleb Greene""Male""Australia"59"Online store""Contoso 512MB MP3 Player E51 S…"Silver""Contoso""Audio""MP4&MP3"612.9912.996.62"AUD"1.3484
36630722020-01-112020-01-11"Isaac Siddins""Male""Australia"25"Contoso Store Western Australi…"Contoso 512MB MP3 Player E51 B…"Blue""Contoso""Audio""MP4&MP3"412.9912.996.62"AUD"1.4545
32570832018-12-012018-12-02"Mike McQueen""Male""United States"56"Online store""Contoso 512MB MP3 Player E51 B…"Blue""Contoso""Audio""MP4&MP3"212.9911.56116.62"USD"1.0

Summing all the numeric columns at once, with a selector:

nbShow df.select(col(SomeNumber)).sum()
shape: (1, 8)
Order NumberLine NumberCustomer AgeQuantityUnit PriceNet PriceUnit CostExchange Rate
i64i64i64i64f64f64f64f64
446601905216195725757435174.1785e63.9286e61.7356e614124.4597

One column, as a Series or in an expression:

let s = df.select("Quantity").toSeries
echo s.sum.item(int)
43517
nbShow df.select(col.Quantity.sum)
shape: (1, 1)
Quantity
i64
43517
nbShow df.select(
  col("Customer Name").first.alias("Cust Name First"),
  col("Customer Name").last.alias("Cust Name Last"))
shape: (1, 2)
Cust Name FirstCust Name Last
strstr
"Eric Kennedy""Billy Ratliff"
nbShow df.select(col(SomeNumber)).describe()
shape: (9, 9)
statisticOrder NumberLine NumberCustomer AgeQuantityUnit PriceNet PriceUnit CostExchange Rate
strf64f64f64f64f64f64f64f64
"count"13915.013915.013915.013915.013915.013915.013915.013915.0
"null_count"0.00.00.00.00.00.00.00.0
"mean"320949.9857711.16385252.156453.127345300.28425282.32739124.7313641.015053
"std"28431.791361.36134919.1338812.233597405.538975381.738847147.9440940.171927
"min"269500.00.019.01.00.950.82650.480.7015
"25%"295902.00.036.01.046.9943.421.920.8965
"50%"319806.01.052.02.0207.987194.9186.681.0
"75%"345106.02.068.04.0361.2336.0160.931.0
"max"371503.06.085.010.03748.53748.51241.9551.5373

There is more...

A condition summed counts the rows where it holds, and filter inside an expression aggregates only some rows:

nbShow df.select((col.Quantity >= 4).sum)
shape: (1, 1)
Quantity
u32
4423
nbShow df.select(col.Quantity.filter(col("Store Name") == "Online store").sum)
shape: (1, 1)
Quantity
i64
25017

Using group by aggregations

How to do it...

agg takes one or more expressions, evaluated per group:

nbShow df
  .groupBy("Brand", maintainOrder = true)
  .agg(col.Quantity.sum.alias("Sum of Quantity"))
  .head()
shape: (5, 2)
BrandSum of Quantity
stri64
"Contoso"11132
"Wide World Importers"3922
"Northwind Traders"638
"Adventure Works "30
"Adventure Works"4616
nbShow df
  .groupBy("Brand")
  .agg(
    col("Unit Price").sum.alias("Sum of Quantity"),
    col("Unit Price").mean.alias("Average Unit Price"))
  .sort("Average Unit Price", descending = true)
  .head()
shape: (5, 3)
BrandSum of QuantityAverage Unit Price
strf64f64
"Fabrikam  "82765.3795.820192
"Contoso "232497.937715.378268
"Adventure Works"908783.8045620.330242
"Litware "33194.085603.528818
"Fabrikam"262239.375557.956117

Two ways to the same mean, plus the first and last values of other columns. The last sort decides the order:

nbShow df
  .groupBy("Brand")
  .agg(
    col("Unit Price").mean.round(2).alias("Average Unit Price"),
    (col("Unit Price").sum / len()).round(2).alias("Average Unit Price 2"),
    col("Customer Name").first,
    col.Category.last)
  .sort("Average Unit Price", descending = true)
  .sort("Brand")
  .head()
shape: (5, 5)
BrandAverage Unit PriceAverage Unit Price 2Customer NameCategory
strf64f64strstr
"A. Datum"280.1280.1"BlaΕΎena SalabovΓ‘""Cameras and camcorders "
"Adventure Works"620.33620.33"Molly Walters""Home Appliances"
"Adventure Works "166.9166.9"James Steinfeld""TV and Video"
"Contoso"150.86150.86"Eric Kennedy""Cell phones"
"Contoso "715.38715.38"Chiquita Boyd""Home Appliances"

The same query on a LazyFrame, from scan_csv:

nbShow scanCsv("data/polars-cookbook/contoso_sales.csv", tryParseDates = true)
  .groupBy("Brand")
  .agg(
    col("Unit Price").mean.round(2).alias("Average Unit Price"),
    (col("Unit Price").sum / len()).round(2).alias("Average Unit Price 2"),
    col("Customer Name").first,
    col.Category.last)
  .sort("Average Unit Price", descending = true)
  .sort("Brand")
  .collect
  .head()
shape: (5, 5)
BrandAverage Unit PriceAverage Unit Price 2Customer NameCategory
strf64f64strstr
"A. Datum"280.1280.1"BlaΕΎena SalabovΓ‘""Cameras and camcorders "
"Adventure Works"620.33620.33"Molly Walters""Home Appliances"
"Adventure Works "166.9166.9"James Steinfeld""TV and Video"
"Contoso"150.86150.86"Eric Kennedy""Cell phones"
"Contoso "715.38715.38"Chiquita Boyd""Home Appliances"

Long brand names are cut in the printed table; a wider string limit shows them whole:

withConfig(fmtStrLengths = 50):
  echo df.select("Brand").unique(maintainOrder = true).head(10)
shape: (10, 1)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Brand                β”‚
β”‚ ---                  β”‚
β”‚ str                  β”‚
β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•‘
β”‚ Contoso              β”‚
β”‚ Wide World Importers β”‚
β”‚ Northwind Traders    β”‚
β”‚ Adventure Works      β”‚
β”‚ Adventure Works      β”‚
β”‚ Southridge Video     β”‚
β”‚ Litware              β”‚
β”‚ Litware              β”‚
β”‚ Fabrikam             β”‚
β”‚ Proseware            β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

There is more...

A group-by can be iterated: one frame per group.

for name, data in df.groupBy("Brand"):
  echo name[0], " ", $typeof(data)
Contoso DataFrame
Wide World Importers DataFrame
Northwind Traders DataFrame
Adventure Works  DataFrame
Adventure Works DataFrame
Southridge Video DataFrame
Litware  DataFrame
Litware DataFrame
Fabrikam DataFrame
Proseware DataFrame
A. Datum DataFrame
Fabrikam   DataFrame
The Phone Company DataFrame
Tailspin Toys DataFrame
Contoso  DataFrame

A column without an aggregation becomes a list per group. maintain_order=True keeps the groups in the order they first appear:

nbShow df
  .groupBy("Brand", maintainOrder = true)
  .agg(col.Quantity)
  .head()
shape: (5, 2)
BrandQuantity
strlist[i64]
"Contoso"[7, 1, … 3]
"Wide World Importers"[2, 8, … 2]
"Northwind Traders"[2, 3, … 2]
"Adventure Works "[2, 3, … 6]
"Adventure Works"[5, 7, … 2]

Grouping keys can be expressions too, here the year of the order date:

nbShow df
  .groupBy(
    [col.Brand,
     col("Customer Country"),
     col("Order Date").dt.year.alias("Order Year")],
    maintainOrder = true)
  .agg(col("Unit Price").mean)
  .head()
shape: (5, 4)
BrandCustomer CountryOrder YearUnit Price
strstri32f64
"Contoso""United States"2017183.832112
"Contoso""Australia"2017206.602904
"Contoso""Australia"2018119.311267
"Contoso""Australia"202078.255
"Contoso""United States"2018144.349852

Aggregating values across multiple columns

How to do it...

The PokΓ©mon table has six stats per PokΓ©mon; their total is a row-wise sum.

df = readCsv("data/polars-cookbook/pokemon.csv")
nbShow df.head()
shape: (5, 13)
#NameType 1Type 2TotalHPAttackDefenseSp. AtkSp. DefSpeedGenerationLegendary
i64strstrstri64i64i64i64i64i64i64i64bool
1"Bulbasaur""Grass""Poison"3184549496565451false
2"Ivysaur""Grass""Poison"4056062638080601false
3"Venusaur""Grass""Poison"525808283100100801false
3"VenusaurMega Venusaur""Grass""Poison"62580100123122120801false
4"Charmander""Fire"null3093952436050651false
nbShow df
  .withColumns(
    sumHorizontal(col("HP", "Attack", "Defense", "Sp. Atk", "Sp. Def", "Speed")).alias("Total 2"))
  .head()
shape: (5, 14)
#NameType 1Type 2TotalHPAttackDefenseSp. AtkSp. DefSpeedGenerationLegendaryTotal 2
i64strstrstri64i64i64i64i64i64i64i64booli64
1"Bulbasaur""Grass""Poison"3184549496565451false318
2"Ivysaur""Grass""Poison"4056062638080601false405
3"Venusaur""Grass""Poison"525808283100100801false525
3"VenusaurMega Venusaur""Grass""Poison"62580100123122120801false625
4"Charmander""Fire"null3093952436050651false309
nbShow df
  .withColumns(
    concatList(col("HP", "Attack", "Defense", "Sp. Atk", "Sp. Def", "Speed")).list.sum.alias("Total 2"))
  .head()
shape: (5, 14)
#NameType 1Type 2TotalHPAttackDefenseSp. AtkSp. DefSpeedGenerationLegendaryTotal 2
i64strstrstri64i64i64i64i64i64i64i64booli64
1"Bulbasaur""Grass""Poison"3184549496565451false318
2"Ivysaur""Grass""Poison"4056062638080601false405
3"Venusaur""Grass""Poison"525808283100100801false525
3"VenusaurMega Venusaur""Grass""Poison"62580100123122120801false625
4"Charmander""Fire"null3093952436050651false309

reduce and fold take a function of two Series. fold starts from a given value (here 100), reduce from the first column:

let cols = ["HP", "Attack", "Defense", "Sp. Atk", "Sp. Def", "Speed"]
nbShow df
  .withColumns(
    reduce(
      f = proc (acc, x: Series): Series = acc + x,
      exprs = col(cols))
    .alias("Total 2"))
  .head()
shape: (5, 14)
#NameType 1Type 2TotalHPAttackDefenseSp. AtkSp. DefSpeedGenerationLegendaryTotal 2
i64strstrstri64i64i64i64i64i64i64i64booli64
1"Bulbasaur""Grass""Poison"3184549496565451false318
2"Ivysaur""Grass""Poison"4056062638080601false405
3"Venusaur""Grass""Poison"525808283100100801false525
3"VenusaurMega Venusaur""Grass""Poison"62580100123122120801false625
4"Charmander""Fire"null3093952436050651false309
nbShow df
  .withColumns(
    fold(
      acc = lit(100),
      f = proc (acc, x: Series): Series = acc + x,
      exprs = col(cols))
    .alias("Total 2"))
  .head()
shape: (5, 14)
#NameType 1Type 2TotalHPAttackDefenseSp. AtkSp. DefSpeedGenerationLegendaryTotal 2
i64strstrstri64i64i64i64i64i64i64i64booli32
1"Bulbasaur""Grass""Poison"3184549496565451false418
2"Ivysaur""Grass""Poison"4056062638080601false505
3"Venusaur""Grass""Poison"525808283100100801false625
3"VenusaurMega Venusaur""Grass""Poison"62580100123122120801false725
4"Charmander""Fire"null3093952436050651false409

There is more...

A fold with and keeps the PokΓ©mon whose stats are all above 80; all_horizontal says the same in one call:

nbShow df
  .filter(
    fold(
      acc = lit(true),
      f = proc (acc, x: Series): Series = acc and x,
      exprs = col(cols) > 80))
  .head()
shape: (4, 13)
#NameType 1Type 2TotalHPAttackDefenseSp. AtkSp. DefSpeedGenerationLegendary
i64strstrstri64i64i64i64i64i64i64i64bool
144"Articuno""Ice""Flying"580908510095125851true
145"Zapdos""Electric""Flying"580909085125901001true
146"Moltres""Fire""Flying"580901009012585901true
150"Mewtwo""Psychic"null68010611090154901301true
nbShow df
  .filter(allHorizontal(col(cols) > 80))
  .head()
shape: (4, 13)
#NameType 1Type 2TotalHPAttackDefenseSp. AtkSp. DefSpeedGenerationLegendary
i64strstrstri64i64i64i64i64i64i64i64bool
144"Articuno""Ice""Flying"580908510095125851true
145"Zapdos""Electric""Flying"580909085125901001true
146"Moltres""Fire""Flying"580901009012585901true
150"Mewtwo""Psychic"null68010611090154901301true

Folding strings concatenates them. Since Type 2 is sometimes empty (null), so is the result in those rows; concat_str does the same:

block:
  let strCombined = fold(
    acc = lit(""),
    f = proc (acc, x: Series): Series = acc + x,
    exprs = col("Name", "Type 1", "Type 2")).alias("Str Combined")
  nbShow df.select(col("Name", "Type 1", "Type 2"), strCombined).head()
shape: (5, 4)
NameType 1Type 2Str Combined
strstrstrstr
"Bulbasaur""Grass""Poison""BulbasaurGrassPoison"
"Ivysaur""Grass""Poison""IvysaurGrassPoison"
"Venusaur""Grass""Poison""VenusaurGrassPoison"
"VenusaurMega Venusaur""Grass""Poison""VenusaurMega VenusaurGrassPois…
"Charmander""Fire"nullnull
nbShow df.select(concatStr([col.Name, col("Type 1"), col("Type 2")])).head()
shape: (5, 1)
Name
str
"BulbasaurGrassPoison"
"IvysaurGrassPoison"
"VenusaurGrassPoison"
"VenusaurMega VenusaurGrassPois…
null

Computing over groups with window functions

How to do it...

Back to the sales, with a sales amount per line:

df = readCsv("data/polars-cookbook/contoso_sales.csv", tryParseDates = true)
df = df.withColumns(
  (col.Quantity * col("Net Price")).round(2).alias("Sales Amount"))
nbShow df.head()
shape: (5, 21)
Order NumberLine NumberOrder DateDelivery DateCustomer NameCustomer GenderCustomer CountryCustomer AgeStore NameProduct NameColorBrandCategorySubcategoryQuantityUnit PriceNet PriceUnit CostCurrency CodeExchange RateSales Amount
i64i64datedatestrstrstri64strstrstrstrstrstri64f64f64f64strf64f64
28480612017-10-182017-10-20"Eric Kennedy""Male""United States"47"Online store""Contoso 512MB MP3 Player E51 S…"Silver""Contoso""Audio""MP4&MP3"711.69110.2885.958"USD"1.072.02
28550612017-10-252017-10-26"George Tooth""Male""Australia"30"Online store""Contoso 512MB MP3 Player E51 S…"Silver""Contoso""Audio""MP4&MP3"111.69111.6915.958"AUD"1.296711.69
31100222018-07-072018-07-12"Caleb Greene""Male""Australia"59"Online store""Contoso 512MB MP3 Player E51 S…"Silver""Contoso""Audio""MP4&MP3"612.9912.996.62"AUD"1.348477.94
36630722020-01-112020-01-11"Isaac Siddins""Male""Australia"25"Contoso Store Western Australi…"Contoso 512MB MP3 Player E51 B…"Blue""Contoso""Audio""MP4&MP3"412.9912.996.62"AUD"1.454551.96
32570832018-12-012018-12-02"Mike McQueen""Male""United States"56"Online store""Contoso 512MB MP3 Player E51 B…"Blue""Contoso""Audio""MP4&MP3"212.9911.56116.62"USD"1.023.12

over computes an aggregation per group but keeps one value per row, so the result has as many rows as the frame:

let salesByCat = df.select(
  col.Category,
  col.Subcategory,
  col("Sales Amount").sum.over("Category").alias("Sales Amt per Cat"))
nbShow salesByCat.head()
shape: (5, 3)
CategorySubcategorySales Amt per Cat
strstrf64
"Audio""MP4&MP3"238355.95
"Audio""MP4&MP3"238355.95
"Audio""MP4&MP3"238355.95
"Audio""MP4&MP3"238355.95
"Audio""MP4&MP3"238355.95
nbShow salesByCat.filter(col.Category == "Audio").unique(maintainOrder = true).head()
shape: (3, 3)
CategorySubcategorySales Amt per Cat
strstrf64
"Audio""MP4&MP3"238355.95
"Audio""Recording Pen"238355.95
"Audio""Bluetooth Headphones"238355.95
echo (df.shape, salesByCat.shape)
((13915, 21), (13915, 3))

Windows over two columns:

nbShow df
  .select(
    col.Category,
    col.Brand,
    col.Subcategory,
    col("Sales Amount").mean.over("Category", "Brand").alias("Avg Sales per Cat and Brand"))
  .filter(col.Category == "Computers")
  .unique()
  .sort(["Brand", "Subcategory"])
  .head(10)
shape: (10, 4)
CategoryBrandSubcategoryAvg Sales per Cat and Brand
strstrstrf64
"Computers""Adventure Works""Desktops"1797.371618
"Computers""Adventure Works""Laptops"1797.371618
"Computers""Adventure Works""Monitors"1797.371618
"Computers""Contoso""Computers Accessories"689.986461
"Computers""Contoso""Projectors & Screens"689.986461
"Computers""Fabrikam""Laptops"1982.065906
"Computers""Proseware""Laptops"1095.304828
"Computers""Proseware""Monitors"1095.304828
"Computers""Proseware""Printers, Scanners & Fax"1095.304828
"Computers""Proseware""Projectors & Screens"1095.304828
import nanuqbook
bookInit()

nbText: "# Data transformation techniques"

attribution polarsCookbook(4, "Data Transformation Techniques",
  "Data is read from `data/polars-cookbook/`. Group-bys followed by `head` keep their " &
  "order (`maintain_order=True`) on both sides, so the two tabs show the same groups. " &
  "Left out: setting the string length through `os.environ`.")

nbText: """
This chapter of the cookbook is about aggregating: over a whole column, per group, across
columns, and over a window. Most of it uses Contoso, a made-up retail chain whose sales
SQLBI generates for Power BI demos, and the last part the PokΓ©mon table.

## Simple aggregations

### How to do it...
"""

tabs """
import polars as pl

df = pl.read_csv('data/polars-cookbook/contoso_sales.csv', try_parse_dates=True)
df.head()
""":
  nbCode:
    import nanuq

    var df = readCsv("data/polars-cookbook/contoso_sales.csv", tryParseDates = true)
    nbShow df.head()

nbText: """
Summing all the numeric columns at once, with a selector:
"""

tabs """
from polars import selectors as cs
(
    df
    .select(cs.numeric())
    .sum()
)
""":
  nbCode:
    nbShow df.select(col(SomeNumber)).sum()

nanuq """
`col(SomeNumber)` is Nanuq's `cs.numeric()`.
"""

nbText: """
One column, as a Series or in an expression:
"""

tabs """
s = df.select('Quantity').to_series()
s.sum()
""":
  nbCode:
    let s = df.select("Quantity").toSeries
    echo s.sum.item(int)

tabs """
df.select(pl.col('Quantity').sum())
""":
  nbCode:
    nbShow df.select(col.Quantity.sum)

tabs """
df.select(
    pl.col('Customer Name').first().alias('Cust Name First'),
    pl.col('Customer Name').last().alias('Cust Name Last')
)
""":
  nbCode:
    nbShow df.select(
      col("Customer Name").first.alias("Cust Name First"),
      col("Customer Name").last.alias("Cust Name Last"))

tabs """
df.select(cs.numeric()).describe()
""":
  nbCode:
    nbShow df.select(col(SomeNumber)).describe()

nbText: """
### There is more...

A condition summed counts the rows where it holds, and `filter` inside an expression
aggregates only some rows:
"""

tabs """
df.select(
    (pl.col('Quantity') >= 4).sum()
)
""":
  nbCode:
    nbShow df.select((col.Quantity >= 4).sum)

tabs """
df.select(
    pl.col('Quantity').filter(pl.col('Store Name')=='Online store').sum()
)
""":
  nbCode:
    nbShow df.select(col.Quantity.filter(col("Store Name") == "Online store").sum)

nbText: """
## Using group by aggregations

### How to do it...

`agg` takes one or more expressions, evaluated per group:
"""

tabs """
(
    df
    .group_by('Brand', maintain_order=True)
    .agg(pl.col('Quantity').sum().alias('Sum of Quantity'))
    .head()
)
""":
  nbCode:
    nbShow df
      .groupBy("Brand", maintainOrder = true)
      .agg(col.Quantity.sum.alias("Sum of Quantity"))
      .head()

tabs """
(
    df
    .group_by('Brand')
    .agg(
        pl.col('Unit Price').sum().alias('Sum of Quantity'),
        pl.col('Unit Price').mean().alias('Average Unit Price'),
    )
    .sort('Average Unit Price', descending=True)
    .head()
)
""":
  nbCode:
    nbShow df
      .groupBy("Brand")
      .agg(
        col("Unit Price").sum.alias("Sum of Quantity"),
        col("Unit Price").mean.alias("Average Unit Price"))
      .sort("Average Unit Price", descending = true)
      .head()

nbText: """
Two ways to the same mean, plus the first and last values of other columns. The last
`sort` decides the order:
"""

tabs """
(
    df
    .group_by('Brand')
    .agg(
        pl.col('Unit Price').mean().round(2).alias('Average Unit Price'),
        (pl.col('Unit Price').sum() / pl.len()).round(2).alias('Average Unit Price 2'),
        pl.col('Customer Name').first(),
        pl.col('Category').last()
    )
    .sort('Average Unit Price', descending=True)
    .sort('Brand')
    .head()
)
""":
  nbCode:
    nbShow df
      .groupBy("Brand")
      .agg(
        col("Unit Price").mean.round(2).alias("Average Unit Price"),
        (col("Unit Price").sum / len()).round(2).alias("Average Unit Price 2"),
        col("Customer Name").first,
        col.Category.last)
      .sort("Average Unit Price", descending = true)
      .sort("Brand")
      .head()

nbText: """
The same query on a LazyFrame, from `scan_csv`:
"""

tabs """
(
    pl.scan_csv('data/polars-cookbook/contoso_sales.csv', try_parse_dates=True)
    .group_by('Brand')
    .agg(
        pl.col('Unit Price').mean().round(2).alias('Average Unit Price'),
        (pl.col('Unit Price').sum() / pl.len()).round(2).alias('Average Unit Price 2'),
        pl.col('Customer Name').first(),
        pl.col('Category').last()
    )
    .sort('Average Unit Price', descending=True)
    .sort('Brand')
    .collect()
    .head()
)
""":
  nbCode:
    nbShow scanCsv("data/polars-cookbook/contoso_sales.csv", tryParseDates = true)
      .groupBy("Brand")
      .agg(
        col("Unit Price").mean.round(2).alias("Average Unit Price"),
        (col("Unit Price").sum / len()).round(2).alias("Average Unit Price 2"),
        col("Customer Name").first,
        col.Category.last)
      .sort("Average Unit Price", descending = true)
      .sort("Brand")
      .collect
      .head()

nbText: """
Long brand names are cut in the printed table; a wider string limit shows them whole:
"""

tabs """
with pl.Config(fmt_str_lengths=50):
    print(df.select('Brand').unique(maintain_order=True).head(10))
""":
  nbCode:
    withConfig(fmtStrLengths = 50):
      echo df.select("Brand").unique(maintainOrder = true).head(10)

nanuq """
The book sets `pl.Config.set_fmt_str_lengths = 50`, which replaces the method instead of
calling it, and then the environment variable `POLARS_FMT_STR_LEN`. Both tabs use the
scoped config instead (`withConfig` in Nim), and keep the order of `unique`.
"""

nbText: """
### There is more...

A group-by can be iterated: one frame per group.
"""

tabs """
for name, data in df.group_by(['Brand'], maintain_order=True):
    print(name[0], type(data))
""":
  nbCode:
    for name, data in df.groupBy("Brand"):
      echo name[0], " ", $typeof(data)

nanuq """
The key of each group is a `seq[string]`, one value per grouping column, like Python's
tuple.
"""

nbText: """
A column without an aggregation becomes a list per group. `maintain_order=True` keeps the
groups in the order they first appear:
"""

tabs """
(
    df
    .group_by('Brand', maintain_order=True)
    .agg(pl.col('Quantity'))
    .head()
)
""":
  nbCode:
    nbShow df
      .groupBy("Brand", maintainOrder = true)
      .agg(col.Quantity)
      .head()

nbText: """
Grouping keys can be expressions too, here the year of the order date:
"""

tabs """
(
    df
    .group_by(
        pl.col('Brand'),
        'Customer Country',
        pl.col('Order Date').dt.year().alias('Order Year'),
        maintain_order=True,
        )
    .agg(pl.col('Unit Price').mean())
    .head()
)
""":
  nbCode:
    nbShow df
      .groupBy(
        [col.Brand,
         col("Customer Country"),
         col("Order Date").dt.year.alias("Order Year")],
        maintainOrder = true)
      .agg(col("Unit Price").mean)
      .head()

nbText: """
## Aggregating values across multiple columns

### How to do it...

The PokΓ©mon table has six stats per PokΓ©mon; their total is a row-wise sum.
"""

tabs """
df = pl.read_csv('data/polars-cookbook/pokemon.csv')
df.head()
""":
  nbCode:
    df = readCsv("data/polars-cookbook/pokemon.csv")
    nbShow df.head()

tabs """
(
    df
    .with_columns(
        pl.sum_horizontal('HP', 'Attack', 'Defense', 'Sp. Atk', 'Sp. Def', 'Speed').alias('Total 2')
    )
    .head()
)
""":
  nbCode:
    nbShow df
      .withColumns(
        sumHorizontal(col("HP", "Attack", "Defense", "Sp. Atk", "Sp. Def", "Speed")).alias("Total 2"))
      .head()

nanuq """
The book starts with `df.select(…).sum_horizontal()`, a frame-level row sum that gives a
Series; Nanuq has the expression only.
"""

tabs """
(
    df
    .with_columns(
        pl.concat_list('HP', 'Attack', 'Defense', 'Sp. Atk', 'Sp. Def', 'Speed').list.sum().alias('Total 2')
    )
    .head()
)
""":
  nbCode:
    nbShow df
      .withColumns(
        concatList(col("HP", "Attack", "Defense", "Sp. Atk", "Sp. Def", "Speed")).list.sum.alias("Total 2"))
      .head()

nbText: """
`reduce` and `fold` take a function of two Series. `fold` starts from a given value (here
100), `reduce` from the first column:
"""

tabs """
cols = ['HP', 'Attack', 'Defense', 'Sp. Atk', 'Sp. Def', 'Speed']
(
    df
    .with_columns(
        pl.reduce(
            function=lambda acc, col: acc + col,
            exprs=pl.col(cols)
        )
        .alias('Total 2')
    )
    .head()
)
""":
  nbCode:
    let cols = ["HP", "Attack", "Defense", "Sp. Atk", "Sp. Def", "Speed"]
    nbShow df
      .withColumns(
        reduce(
          f = proc (acc, x: Series): Series = acc + x,
          exprs = col(cols))
        .alias("Total 2"))
      .head()

tabs """
(
    df
    .with_columns(
        pl.fold(
            acc=pl.lit(100),
            function=lambda acc, col: acc + col,
            exprs=pl.col(cols)
        )
        .alias('Total 2')
    )
    .head()
)
""":
  nbCode:
    nbShow df
      .withColumns(
        fold(
          acc = lit(100),
          f = proc (acc, x: Series): Series = acc + x,
          exprs = col(cols))
        .alias("Total 2"))
      .head()

nbText: """
### There is more...

A fold with *and* keeps the PokΓ©mon whose stats are all above 80; `all_horizontal` says
the same in one call:
"""

tabs """
(
    df
    .filter(
        pl.fold(
            acc=pl.lit(True),
            function=lambda acc, col: acc & col,
            exprs=pl.col(cols) > 80
        )
    )
    .head()
)
""":
  nbCode:
    nbShow df
      .filter(
        fold(
          acc = lit(true),
          f = proc (acc, x: Series): Series = acc and x,
          exprs = col(cols) > 80))
      .head()

tabs """
(
    df
    .filter(
        pl.all_horizontal(pl.col(cols) > 80)
    )
    .head()
)
""":
  nbCode:
    nbShow df
      .filter(allHorizontal(col(cols) > 80))
      .head()

nbText: """
Folding strings concatenates them. Since `Type 2` is sometimes empty (null), so is the
result in those rows; `concat_str` does the same:
"""

tabs """
str_cols = ['Name', 'Type 1', 'Type 2']
str_combined = pl.fold(acc=pl.lit(''), function=lambda acc, col: acc + col, exprs=str_cols).alias('Str Combined')
str_cols.append(str_combined)
df.select(str_cols).head()
""":
  nbCode:
    block:
      let strCombined = fold(
        acc = lit(""),
        f = proc (acc, x: Series): Series = acc + x,
        exprs = col("Name", "Type 1", "Type 2")).alias("Str Combined")
      nbShow df.select(col("Name", "Type 1", "Type 2"), strCombined).head()

tabs """
str_cols = ['Name', 'Type 1', 'Type 2']
df.select(pl.concat_str(str_cols)).head()
""":
  nbCode:
    nbShow df.select(concatStr([col.Name, col("Type 1"), col("Type 2")])).head()

nbText: """
## Computing over groups with window functions

### How to do it...

Back to the sales, with a sales amount per line:
"""

tabs """
df = pl.read_csv('data/polars-cookbook/contoso_sales.csv', try_parse_dates=True)
df = df.with_columns(
    (pl.col('Quantity') * pl.col('Net Price')).round(2).alias('Sales Amount')
)
df.head()
""":
  nbCode:
    df = readCsv("data/polars-cookbook/contoso_sales.csv", tryParseDates = true)
    df = df.withColumns(
      (col.Quantity * col("Net Price")).round(2).alias("Sales Amount"))
    nbShow df.head()

nbText: """
`over` computes an aggregation per group but keeps one value per row, so the result has as
many rows as the frame:
"""

tabs """
sales_by_cat = df.select(
    'Category',
    'Subcategory',
    pl.col('Sales Amount').sum().over('Category').alias('Sales Amt per Cat')
)
sales_by_cat.head()
""":
  nbCode:
    let salesByCat = df.select(
      col.Category,
      col.Subcategory,
      col("Sales Amount").sum.over("Category").alias("Sales Amt per Cat"))
    nbShow salesByCat.head()

tabs """
sales_by_cat.filter(pl.col('Category')=='Audio').unique(maintain_order=True).head()
""":
  nbCode:
    nbShow salesByCat.filter(col.Category == "Audio").unique(maintainOrder = true).head()

tabs """
df.shape, sales_by_cat.shape
""":
  nbCode:
    echo (df.shape, salesByCat.shape)

nbText: """
Windows over two columns:
"""

tabs """
(
    df
    .select(
        'Category',
        'Brand',
        'Subcategory',
        pl.col('Sales Amount').mean().over('Category', 'Brand').alias('Avg Sales per Cat and Brand')
    )
    .filter(
        (pl.col('Category')=='Computers')
    )
    .unique()
    .sort('Brand', 'Subcategory')
    .head(10)
)
""":
  nbCode:
    nbShow df
      .select(
        col.Category,
        col.Brand,
        col.Subcategory,
        col("Sales Amount").mean.over("Category", "Brand").alias("Avg Sales per Cat and Brand"))
      .filter(col.Category == "Computers")
      .unique()
      .sort(["Brand", "Subcategory"])
      .head(10)

nanuq """
The book sorts by `Brand` only, which leaves the order within a brand open; both tabs sort
by subcategory as well.
"""

bookSave()
Made with nimib and nimibook. Blocks marked "ran" were executed when this page was built.