Data transformation techniques
π»ββοΈ About this port
Ported from Chapter 4, βData Transformation Techniquesβ, of Polars Cookbook (Packt, 2024) by Yuki Kakegawa, licensed under MIT . The licence covers the code, not the book's text: the code, section headings and data are the original's, the text between them is the Nanuq book's own. The book explains it all much better. 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.
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...
π Nim π Python
import nanuq
var df = readCsv("data/polars-cookbook/contoso_sales.csv" , tryParseDates = true )
nbShow df.head()
shape: (5, 20) Order Number Line Number Order Date Delivery Date Customer Name Customer Gender Customer Country Customer Age Store Name Product Name Color Brand Category Subcategory Quantity Unit Price Net Price Unit Cost Currency Code Exchange Rate i64 i64 date date str str str i64 str str str str str str i64 f64 f64 f64 str f64 284806 1 2017-10-18 2017-10-20 "Eric Kennedy" "Male" "United States" 47 "Online store" "Contoso 512MB MP3 Player E51 S⦠"Silver" "Contoso" "Audio" "MP4&MP3" 7 11.691 10.288 5.958 "USD" 1.0 285506 1 2017-10-25 2017-10-26 "George Tooth" "Male" "Australia" 30 "Online store" "Contoso 512MB MP3 Player E51 S⦠"Silver" "Contoso" "Audio" "MP4&MP3" 1 11.691 11.691 5.958 "AUD" 1.2967 311002 2 2018-07-07 2018-07-12 "Caleb Greene" "Male" "Australia" 59 "Online store" "Contoso 512MB MP3 Player E51 S⦠"Silver" "Contoso" "Audio" "MP4&MP3" 6 12.99 12.99 6.62 "AUD" 1.3484 366307 2 2020-01-11 2020-01-11 "Isaac Siddins" "Male" "Australia" 25 "Contoso Store Western Australi⦠"Contoso 512MB MP3 Player E51 B⦠"Blue" "Contoso" "Audio" "MP4&MP3" 4 12.99 12.99 6.62 "AUD" 1.4545 325708 3 2018-12-01 2018-12-02 "Mike McQueen" "Male" "United States" 56 "Online store" "Contoso 512MB MP3 Player E51 B⦠"Blue" "Contoso" "Audio" "MP4&MP3" 2 12.99 11.5611 6.62 "USD" 1.0
import polars as pl
df = pl.read_csv('data/polars-cookbook/contoso_sales.csv', try_parse_dates=True)
df.head()
shape: (5, 20) Order Number Line Number Order Date Delivery Date Customer Name Customer Gender Customer Country Customer Age Store Name Product Name Color Brand Category Subcategory Quantity Unit Price Net Price Unit Cost Currency Code Exchange Rate i64 i64 date date str str str i64 str str str str str str i64 f64 f64 f64 str f64 284806 1 2017-10-18 2017-10-20 "Eric Kennedy" "Male" "United States" 47 "Online store" "Contoso 512MB MP3 Player E51 S⦠"Silver" "Contoso" "Audio" "MP4&MP3" 7 11.691 10.288 5.958 "USD" 1.0 285506 1 2017-10-25 2017-10-26 "George Tooth" "Male" "Australia" 30 "Online store" "Contoso 512MB MP3 Player E51 S⦠"Silver" "Contoso" "Audio" "MP4&MP3" 1 11.691 11.691 5.958 "AUD" 1.2967 311002 2 2018-07-07 2018-07-12 "Caleb Greene" "Male" "Australia" 59 "Online store" "Contoso 512MB MP3 Player E51 S⦠"Silver" "Contoso" "Audio" "MP4&MP3" 6 12.99 12.99 6.62 "AUD" 1.3484 366307 2 2020-01-11 2020-01-11 "Isaac Siddins" "Male" "Australia" 25 "Contoso Store Western Australi⦠"Contoso 512MB MP3 Player E51 B⦠"Blue" "Contoso" "Audio" "MP4&MP3" 4 12.99 12.99 6.62 "AUD" 1.4545 325708 3 2018-12-01 2018-12-02 "Mike McQueen" "Male" "United States" 56 "Online store" "Contoso 512MB MP3 Player E51 B⦠"Blue" "Contoso" "Audio" "MP4&MP3" 2 12.99 11.5611 6.62 "USD" 1.0
Summing all the numeric columns at once, with a selector:
π Nim π Python
nbShow df.select(col(SomeNumber )).sum()
shape: (1, 8) Order Number Line Number Customer Age Quantity Unit Price Net Price Unit Cost Exchange Rate i64 i64 i64 i64 f64 f64 f64 f64 4466019052 16195 725757 43517 4.1785e6 3.9286e6 1.7356e6 14124.4597
from polars import selectors as cs
(
df
.select(cs.numeric())
.sum()
)
shape: (1, 8) Order Number Line Number Customer Age Quantity Unit Price Net Price Unit Cost Exchange Rate i64 i64 i64 i64 f64 f64 f64 f64 4466019052 16195 725757 43517 4.1785e6 3.9286e6 1.7356e6 14124.4597
One column, as a Series or in an expression:
π Nim π Python
let s = df.select("Quantity" ).toSeries
echo s.sum.item(int )
43517
s = df.select('Quantity').to_series()
s.sum()43517
π Nim π Python
nbShow df.select(col.Quantity .sum)
df.select(pl.col('Quantity').sum())
π Nim π Python
nbShow df.select(
col("Customer Name" ).first.alias("Cust Name First" ),
col("Customer Name" ).last.alias("Cust Name Last" ))
shape: (1, 2) Cust Name First Cust Name Last str str "Eric Kennedy" "Billy Ratliff"
df.select(
pl.col('Customer Name').first().alias('Cust Name First'),
pl.col('Customer Name').last().alias('Cust Name Last')
)
shape: (1, 2) Cust Name First Cust Name Last str str "Eric Kennedy" "Billy Ratliff"
π Nim π Python
nbShow df.select(col(SomeNumber )).describe()
shape: (9, 9) statistic Order Number Line Number Customer Age Quantity Unit Price Net Price Unit Cost Exchange Rate str f64 f64 f64 f64 f64 f64 f64 f64 "count" 13915.0 13915.0 13915.0 13915.0 13915.0 13915.0 13915.0 13915.0 "null_count" 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 "mean" 320949.985771 1.163852 52.15645 3.127345 300.28425 282.32739 124.731364 1.015053 "std" 28431.79136 1.361349 19.133881 2.233597 405.538975 381.738847 147.944094 0.171927 "min" 269500.0 0.0 19.0 1.0 0.95 0.8265 0.48 0.7015 "25%" 295902.0 0.0 36.0 1.0 46.99 43.4 21.92 0.8965 "50%" 319806.0 1.0 52.0 2.0 207.987 194.91 86.68 1.0 "75%" 345106.0 2.0 68.0 4.0 361.2 336.0 160.93 1.0 "max" 371503.0 6.0 85.0 10.0 3748.5 3748.5 1241.955 1.5373
df.select(cs.numeric()).describe()
shape: (9, 9) statistic Order Number Line Number Customer Age Quantity Unit Price Net Price Unit Cost Exchange Rate str f64 f64 f64 f64 f64 f64 f64 f64 "count" 13915.0 13915.0 13915.0 13915.0 13915.0 13915.0 13915.0 13915.0 "null_count" 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 "mean" 320949.985771 1.163852 52.15645 3.127345 300.28425 282.32739 124.731364 1.015053 "std" 28431.79136 1.361349 19.133881 2.233597 405.538975 381.738847 147.944094 0.171927 "min" 269500.0 0.0 19.0 1.0 0.95 0.8265 0.48 0.7015 "25%" 295902.0 0.0 36.0 1.0 46.99 43.4 21.92 0.8965 "50%" 319806.0 1.0 52.0 2.0 207.987 194.91 86.68 1.0 "75%" 345106.0 2.0 68.0 4.0 361.2 336.0 160.93 1.0 "max" 371503.0 6.0 85.0 10.0 3748.5 3748.5 1241.955 1.5373
There is more...
A condition summed counts the rows where it holds, and filter inside an expression
aggregates only some rows:
π Nim π Python
nbShow df.select((col.Quantity >= 4 ).sum)
df.select(
(pl.col('Quantity') >= 4).sum()
)
π Nim π Python
nbShow df.select(col.Quantity .filter(col("Store Name" ) == "Online store" ).sum)
df.select(
pl.col('Quantity').filter(pl.col('Store Name')=='Online store').sum()
)
Using group by aggregations
How to do it...
agg takes one or more expressions, evaluated per group:
π Nim π Python
nbShow df
.groupBy("Brand" , maintainOrder = true )
.agg(col.Quantity .sum.alias("Sum of Quantity" ))
.head()
shape: (5, 2) Brand Sum of Quantity str i64 "Contoso" 11132 "Wide World Importers" 3922 "Northwind Traders" 638 "Adventure Works " 30 "Adventure Works" 4616
(
df
.group_by('Brand', maintain_order=True)
.agg(pl.col('Quantity').sum().alias('Sum of Quantity'))
.head()
)
shape: (5, 2) Brand Sum of Quantity str i64 "Contoso" 11132 "Wide World Importers" 3922 "Northwind Traders" 638 "Adventure Works " 30 "Adventure Works" 4616
π Nim π Python
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) Brand Sum of Quantity Average Unit Price str f64 f64 "Fabrikam " 82765.3 795.820192 "Contoso " 232497.937 715.378268 "Adventure Works" 908783.8045 620.330242 "Litware " 33194.085 603.528818 "Fabrikam" 262239.375 557.956117
(
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()
)
shape: (5, 3) Brand Sum of Quantity Average Unit Price str f64 f64 "Fabrikam " 82765.3 795.820192 "Contoso " 232497.937 715.378268 "Adventure Works" 908783.8045 620.330242 "Litware " 33194.085 603.528818 "Fabrikam" 262239.375 557.956117
Two ways to the same mean, plus the first and last values of other columns. The last
sort decides the order:
π Nim π Python
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) Brand Average Unit Price Average Unit Price 2 Customer Name Category str f64 f64 str str "A. Datum" 280.1 280.1 "BlaΕΎena SalabovΓ‘" "Cameras and camcorders " "Adventure Works" 620.33 620.33 "Molly Walters" "Home Appliances" "Adventure Works " 166.9 166.9 "James Steinfeld" "TV and Video" "Contoso" 150.86 150.86 "Eric Kennedy" "Cell phones" "Contoso " 715.38 715.38 "Chiquita Boyd" "Home Appliances"
(
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()
)
shape: (5, 5) Brand Average Unit Price Average Unit Price 2 Customer Name Category str f64 f64 str str "A. Datum" 280.1 280.1 "BlaΕΎena SalabovΓ‘" "Cameras and camcorders " "Adventure Works" 620.33 620.33 "Molly Walters" "Home Appliances" "Adventure Works " 166.9 166.9 "James Steinfeld" "TV and Video" "Contoso" 150.86 150.86 "Eric Kennedy" "Cell phones" "Contoso " 715.38 715.38 "Chiquita Boyd" "Home Appliances"
The same query on a LazyFrame, from scan_csv:
π Nim π Python
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) Brand Average Unit Price Average Unit Price 2 Customer Name Category str f64 f64 str str "A. Datum" 280.1 280.1 "BlaΕΎena SalabovΓ‘" "Cameras and camcorders " "Adventure Works" 620.33 620.33 "Molly Walters" "Home Appliances" "Adventure Works " 166.9 166.9 "James Steinfeld" "TV and Video" "Contoso" 150.86 150.86 "Eric Kennedy" "Cell phones" "Contoso " 715.38 715.38 "Chiquita Boyd" "Home Appliances"
(
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()
)
shape: (5, 5) Brand Average Unit Price Average Unit Price 2 Customer Name Category str f64 f64 str str "A. Datum" 280.1 280.1 "BlaΕΎena SalabovΓ‘" "Cameras and camcorders " "Adventure Works" 620.33 620.33 "Molly Walters" "Home Appliances" "Adventure Works " 166.9 166.9 "James Steinfeld" "TV and Video" "Contoso" 150.86 150.86 "Eric Kennedy" "Cell phones" "Contoso " 715.38 715.38 "Chiquita Boyd" "Home Appliances"
Long brand names are cut in the printed table; a wider string limit shows them whole:
π Nim π Python
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 β
ββββββββββββββββββββββββ
with pl.Config(fmt_str_lengths=50):
print(df.select('Brand').unique(maintain_order=True).head(10))shape: (10, 1)
ββββββββββββββββββββββββ
β Brand β
β --- β
β str β
ββββββββββββββββββββββββ‘
β Contoso β
β Wide World Importers β
β Northwind Traders β
β Adventure Works β
β Adventure Works β
β Southridge Video β
β Litware β
β Litware β
β Fabrikam β
β Proseware β
ββββββββββββββββββββββββ
π»ββοΈ 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.
There is more...
A group-by can be iterated: one frame per group.
π Nim π Python
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
for name, data in df.group_by(['Brand'], maintain_order=True):
print(name[0], type(data))Contoso <class 'polars.dataframe.frame.DataFrame'>
Wide World Importers <class 'polars.dataframe.frame.DataFrame'>
Northwind Traders <class 'polars.dataframe.frame.DataFrame'>
Adventure Works <class 'polars.dataframe.frame.DataFrame'>
Adventure Works <class 'polars.dataframe.frame.DataFrame'>
Southridge Video <class 'polars.dataframe.frame.DataFrame'>
Litware <class 'polars.dataframe.frame.DataFrame'>
Litware <class 'polars.dataframe.frame.DataFrame'>
Fabrikam <class 'polars.dataframe.frame.DataFrame'>
Proseware <class 'polars.dataframe.frame.DataFrame'>
A. Datum <class 'polars.dataframe.frame.DataFrame'>
Fabrikam <class 'polars.dataframe.frame.DataFrame'>
The Phone Company <class 'polars.dataframe.frame.DataFrame'>
Tailspin Toys <class 'polars.dataframe.frame.DataFrame'>
Contoso <class 'polars.dataframe.frame.DataFrame'>
π»ββοΈ Nanuq
The key of each group is a seq[string], one value per grouping column, like Python's
tuple.
A column without an aggregation becomes a list per group. maintain_order=True keeps the
groups in the order they first appear:
π Nim π Python
nbShow df
.groupBy("Brand" , maintainOrder = true )
.agg(col.Quantity )
.head()
shape: (5, 2) Brand Quantity str list[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]
(
df
.group_by('Brand', maintain_order=True)
.agg(pl.col('Quantity'))
.head()
)
shape: (5, 2) Brand Quantity str list[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:
π Nim π Python
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) Brand Customer Country Order Year Unit Price str str i32 f64 "Contoso" "United States" 2017 183.832112 "Contoso" "Australia" 2017 206.602904 "Contoso" "Australia" 2018 119.311267 "Contoso" "Australia" 2020 78.255 "Contoso" "United States" 2018 144.349852
(
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()
)
shape: (5, 4) Brand Customer Country Order Year Unit Price str str i32 f64 "Contoso" "United States" 2017 183.832112 "Contoso" "Australia" 2017 206.602904 "Contoso" "Australia" 2018 119.311267 "Contoso" "Australia" 2020 78.255 "Contoso" "United States" 2018 144.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.
π Nim π Python
df = readCsv("data/polars-cookbook/pokemon.csv" )
nbShow df.head()
shape: (5, 13) # Name Type 1 Type 2 Total HP Attack Defense Sp. Atk Sp. Def Speed Generation Legendary i64 str str str i64 i64 i64 i64 i64 i64 i64 i64 bool 1 "Bulbasaur" "Grass" "Poison" 318 45 49 49 65 65 45 1 false 2 "Ivysaur" "Grass" "Poison" 405 60 62 63 80 80 60 1 false 3 "Venusaur" "Grass" "Poison" 525 80 82 83 100 100 80 1 false 3 "VenusaurMega Venusaur" "Grass" "Poison" 625 80 100 123 122 120 80 1 false 4 "Charmander" "Fire" null 309 39 52 43 60 50 65 1 false
df = pl.read_csv('data/polars-cookbook/pokemon.csv')
df.head()
shape: (5, 13) # Name Type 1 Type 2 Total HP Attack Defense Sp. Atk Sp. Def Speed Generation Legendary i64 str str str i64 i64 i64 i64 i64 i64 i64 i64 bool 1 "Bulbasaur" "Grass" "Poison" 318 45 49 49 65 65 45 1 false 2 "Ivysaur" "Grass" "Poison" 405 60 62 63 80 80 60 1 false 3 "Venusaur" "Grass" "Poison" 525 80 82 83 100 100 80 1 false 3 "VenusaurMega Venusaur" "Grass" "Poison" 625 80 100 123 122 120 80 1 false 4 "Charmander" "Fire" null 309 39 52 43 60 50 65 1 false
π Nim π Python
nbShow df
.withColumns(
sumHorizontal(col("HP" , "Attack" , "Defense" , "Sp. Atk" , "Sp. Def" , "Speed" )).alias("Total 2" ))
.head()
shape: (5, 14) # Name Type 1 Type 2 Total HP Attack Defense Sp. Atk Sp. Def Speed Generation Legendary Total 2 i64 str str str i64 i64 i64 i64 i64 i64 i64 i64 bool i64 1 "Bulbasaur" "Grass" "Poison" 318 45 49 49 65 65 45 1 false 318 2 "Ivysaur" "Grass" "Poison" 405 60 62 63 80 80 60 1 false 405 3 "Venusaur" "Grass" "Poison" 525 80 82 83 100 100 80 1 false 525 3 "VenusaurMega Venusaur" "Grass" "Poison" 625 80 100 123 122 120 80 1 false 625 4 "Charmander" "Fire" null 309 39 52 43 60 50 65 1 false 309
(
df
.with_columns(
pl.sum_horizontal('HP', 'Attack', 'Defense', 'Sp. Atk', 'Sp. Def', 'Speed').alias('Total 2')
)
.head()
)
shape: (5, 14) # Name Type 1 Type 2 Total HP Attack Defense Sp. Atk Sp. Def Speed Generation Legendary Total 2 i64 str str str i64 i64 i64 i64 i64 i64 i64 i64 bool i64 1 "Bulbasaur" "Grass" "Poison" 318 45 49 49 65 65 45 1 false 318 2 "Ivysaur" "Grass" "Poison" 405 60 62 63 80 80 60 1 false 405 3 "Venusaur" "Grass" "Poison" 525 80 82 83 100 100 80 1 false 525 3 "VenusaurMega Venusaur" "Grass" "Poison" 625 80 100 123 122 120 80 1 false 625 4 "Charmander" "Fire" null 309 39 52 43 60 50 65 1 false 309
π»ββοΈ Nanuq
The book starts with df.select(β¦).sum_horizontal(), a frame-level row sum that gives a
Series; Nanuq has the expression only.
π Nim π Python
nbShow df
.withColumns(
concatList(col("HP" , "Attack" , "Defense" , "Sp. Atk" , "Sp. Def" , "Speed" )).list.sum.alias("Total 2" ))
.head()
shape: (5, 14) # Name Type 1 Type 2 Total HP Attack Defense Sp. Atk Sp. Def Speed Generation Legendary Total 2 i64 str str str i64 i64 i64 i64 i64 i64 i64 i64 bool i64 1 "Bulbasaur" "Grass" "Poison" 318 45 49 49 65 65 45 1 false 318 2 "Ivysaur" "Grass" "Poison" 405 60 62 63 80 80 60 1 false 405 3 "Venusaur" "Grass" "Poison" 525 80 82 83 100 100 80 1 false 525 3 "VenusaurMega Venusaur" "Grass" "Poison" 625 80 100 123 122 120 80 1 false 625 4 "Charmander" "Fire" null 309 39 52 43 60 50 65 1 false 309
(
df
.with_columns(
pl.concat_list('HP', 'Attack', 'Defense', 'Sp. Atk', 'Sp. Def', 'Speed').list.sum().alias('Total 2')
)
.head()
)
shape: (5, 14) # Name Type 1 Type 2 Total HP Attack Defense Sp. Atk Sp. Def Speed Generation Legendary Total 2 i64 str str str i64 i64 i64 i64 i64 i64 i64 i64 bool i64 1 "Bulbasaur" "Grass" "Poison" 318 45 49 49 65 65 45 1 false 318 2 "Ivysaur" "Grass" "Poison" 405 60 62 63 80 80 60 1 false 405 3 "Venusaur" "Grass" "Poison" 525 80 82 83 100 100 80 1 false 525 3 "VenusaurMega Venusaur" "Grass" "Poison" 625 80 100 123 122 120 80 1 false 625 4 "Charmander" "Fire" null 309 39 52 43 60 50 65 1 false 309
reduce and fold take a function of two Series. fold starts from a given value (here
100), reduce from the first column:
π Nim π Python
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) # Name Type 1 Type 2 Total HP Attack Defense Sp. Atk Sp. Def Speed Generation Legendary Total 2 i64 str str str i64 i64 i64 i64 i64 i64 i64 i64 bool i64 1 "Bulbasaur" "Grass" "Poison" 318 45 49 49 65 65 45 1 false 318 2 "Ivysaur" "Grass" "Poison" 405 60 62 63 80 80 60 1 false 405 3 "Venusaur" "Grass" "Poison" 525 80 82 83 100 100 80 1 false 525 3 "VenusaurMega Venusaur" "Grass" "Poison" 625 80 100 123 122 120 80 1 false 625 4 "Charmander" "Fire" null 309 39 52 43 60 50 65 1 false 309
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()
)
shape: (5, 14) # Name Type 1 Type 2 Total HP Attack Defense Sp. Atk Sp. Def Speed Generation Legendary Total 2 i64 str str str i64 i64 i64 i64 i64 i64 i64 i64 bool i64 1 "Bulbasaur" "Grass" "Poison" 318 45 49 49 65 65 45 1 false 318 2 "Ivysaur" "Grass" "Poison" 405 60 62 63 80 80 60 1 false 405 3 "Venusaur" "Grass" "Poison" 525 80 82 83 100 100 80 1 false 525 3 "VenusaurMega Venusaur" "Grass" "Poison" 625 80 100 123 122 120 80 1 false 625 4 "Charmander" "Fire" null 309 39 52 43 60 50 65 1 false 309
π Nim π Python
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) # Name Type 1 Type 2 Total HP Attack Defense Sp. Atk Sp. Def Speed Generation Legendary Total 2 i64 str str str i64 i64 i64 i64 i64 i64 i64 i64 bool i32 1 "Bulbasaur" "Grass" "Poison" 318 45 49 49 65 65 45 1 false 418 2 "Ivysaur" "Grass" "Poison" 405 60 62 63 80 80 60 1 false 505 3 "Venusaur" "Grass" "Poison" 525 80 82 83 100 100 80 1 false 625 3 "VenusaurMega Venusaur" "Grass" "Poison" 625 80 100 123 122 120 80 1 false 725 4 "Charmander" "Fire" null 309 39 52 43 60 50 65 1 false 409
(
df
.with_columns(
pl.fold(
acc=pl.lit(100),
function=lambda acc, col: acc + col,
exprs=pl.col(cols)
)
.alias('Total 2')
)
.head()
)
shape: (5, 14) # Name Type 1 Type 2 Total HP Attack Defense Sp. Atk Sp. Def Speed Generation Legendary Total 2 i64 str str str i64 i64 i64 i64 i64 i64 i64 i64 bool i32 1 "Bulbasaur" "Grass" "Poison" 318 45 49 49 65 65 45 1 false 418 2 "Ivysaur" "Grass" "Poison" 405 60 62 63 80 80 60 1 false 505 3 "Venusaur" "Grass" "Poison" 525 80 82 83 100 100 80 1 false 625 3 "VenusaurMega Venusaur" "Grass" "Poison" 625 80 100 123 122 120 80 1 false 725 4 "Charmander" "Fire" null 309 39 52 43 60 50 65 1 false 409
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:
π Nim π Python
nbShow df
.filter(
fold(
acc = lit(true ),
f = proc (acc, x: Series ): Series = acc and x,
exprs = col(cols) > 80 ))
.head()
shape: (4, 13) # Name Type 1 Type 2 Total HP Attack Defense Sp. Atk Sp. Def Speed Generation Legendary i64 str str str i64 i64 i64 i64 i64 i64 i64 i64 bool 144 "Articuno" "Ice" "Flying" 580 90 85 100 95 125 85 1 true 145 "Zapdos" "Electric" "Flying" 580 90 90 85 125 90 100 1 true 146 "Moltres" "Fire" "Flying" 580 90 100 90 125 85 90 1 true 150 "Mewtwo" "Psychic" null 680 106 110 90 154 90 130 1 true
(
df
.filter(
pl.fold(
acc=pl.lit(True),
function=lambda acc, col: acc & col,
exprs=pl.col(cols) > 80
)
)
.head()
)
shape: (4, 13) # Name Type 1 Type 2 Total HP Attack Defense Sp. Atk Sp. Def Speed Generation Legendary i64 str str str i64 i64 i64 i64 i64 i64 i64 i64 bool 144 "Articuno" "Ice" "Flying" 580 90 85 100 95 125 85 1 true 145 "Zapdos" "Electric" "Flying" 580 90 90 85 125 90 100 1 true 146 "Moltres" "Fire" "Flying" 580 90 100 90 125 85 90 1 true 150 "Mewtwo" "Psychic" null 680 106 110 90 154 90 130 1 true
π Nim π Python
nbShow df
.filter(allHorizontal(col(cols) > 80 ))
.head()
shape: (4, 13) # Name Type 1 Type 2 Total HP Attack Defense Sp. Atk Sp. Def Speed Generation Legendary i64 str str str i64 i64 i64 i64 i64 i64 i64 i64 bool 144 "Articuno" "Ice" "Flying" 580 90 85 100 95 125 85 1 true 145 "Zapdos" "Electric" "Flying" 580 90 90 85 125 90 100 1 true 146 "Moltres" "Fire" "Flying" 580 90 100 90 125 85 90 1 true 150 "Mewtwo" "Psychic" null 680 106 110 90 154 90 130 1 true
(
df
.filter(
pl.all_horizontal(pl.col(cols) > 80)
)
.head()
)
shape: (4, 13) # Name Type 1 Type 2 Total HP Attack Defense Sp. Atk Sp. Def Speed Generation Legendary i64 str str str i64 i64 i64 i64 i64 i64 i64 i64 bool 144 "Articuno" "Ice" "Flying" 580 90 85 100 95 125 85 1 true 145 "Zapdos" "Electric" "Flying" 580 90 90 85 125 90 100 1 true 146 "Moltres" "Fire" "Flying" 580 90 100 90 125 85 90 1 true 150 "Mewtwo" "Psychic" null 680 106 110 90 154 90 130 1 true
Folding strings concatenates them. Since Type 2 is sometimes empty (null), so is the
result in those rows; concat_str does the same:
π Nim π Python
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) Name Type 1 Type 2 Str Combined str str str str "Bulbasaur" "Grass" "Poison" "BulbasaurGrassPoison" "Ivysaur" "Grass" "Poison" "IvysaurGrassPoison" "Venusaur" "Grass" "Poison" "VenusaurGrassPoison" "VenusaurMega Venusaur" "Grass" "Poison" "VenusaurMega VenusaurGrassPois⦠"Charmander" "Fire" null null
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()
shape: (5, 4) Name Type 1 Type 2 Str Combined str str str str "Bulbasaur" "Grass" "Poison" "BulbasaurGrassPoison" "Ivysaur" "Grass" "Poison" "IvysaurGrassPoison" "Venusaur" "Grass" "Poison" "VenusaurGrassPoison" "VenusaurMega Venusaur" "Grass" "Poison" "VenusaurMega VenusaurGrassPois⦠"Charmander" "Fire" null null
π Nim π Python
nbShow df.select(concatStr([col.Name , col("Type 1" ), col("Type 2" )])).head()
shape: (5, 1) Name str "BulbasaurGrassPoison" "IvysaurGrassPoison" "VenusaurGrassPoison" "VenusaurMega VenusaurGrassPois⦠null
str_cols = ['Name', 'Type 1', 'Type 2']
df.select(pl.concat_str(str_cols)).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:
π Nim π Python
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 Number Line Number Order Date Delivery Date Customer Name Customer Gender Customer Country Customer Age Store Name Product Name Color Brand Category Subcategory Quantity Unit Price Net Price Unit Cost Currency Code Exchange Rate Sales Amount i64 i64 date date str str str i64 str str str str str str i64 f64 f64 f64 str f64 f64 284806 1 2017-10-18 2017-10-20 "Eric Kennedy" "Male" "United States" 47 "Online store" "Contoso 512MB MP3 Player E51 S⦠"Silver" "Contoso" "Audio" "MP4&MP3" 7 11.691 10.288 5.958 "USD" 1.0 72.02 285506 1 2017-10-25 2017-10-26 "George Tooth" "Male" "Australia" 30 "Online store" "Contoso 512MB MP3 Player E51 S⦠"Silver" "Contoso" "Audio" "MP4&MP3" 1 11.691 11.691 5.958 "AUD" 1.2967 11.69 311002 2 2018-07-07 2018-07-12 "Caleb Greene" "Male" "Australia" 59 "Online store" "Contoso 512MB MP3 Player E51 S⦠"Silver" "Contoso" "Audio" "MP4&MP3" 6 12.99 12.99 6.62 "AUD" 1.3484 77.94 366307 2 2020-01-11 2020-01-11 "Isaac Siddins" "Male" "Australia" 25 "Contoso Store Western Australi⦠"Contoso 512MB MP3 Player E51 B⦠"Blue" "Contoso" "Audio" "MP4&MP3" 4 12.99 12.99 6.62 "AUD" 1.4545 51.96 325708 3 2018-12-01 2018-12-02 "Mike McQueen" "Male" "United States" 56 "Online store" "Contoso 512MB MP3 Player E51 B⦠"Blue" "Contoso" "Audio" "MP4&MP3" 2 12.99 11.5611 6.62 "USD" 1.0 23.12
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()
shape: (5, 21) Order Number Line Number Order Date Delivery Date Customer Name Customer Gender Customer Country Customer Age Store Name Product Name Color Brand Category Subcategory Quantity Unit Price Net Price Unit Cost Currency Code Exchange Rate Sales Amount i64 i64 date date str str str i64 str str str str str str i64 f64 f64 f64 str f64 f64 284806 1 2017-10-18 2017-10-20 "Eric Kennedy" "Male" "United States" 47 "Online store" "Contoso 512MB MP3 Player E51 S⦠"Silver" "Contoso" "Audio" "MP4&MP3" 7 11.691 10.288 5.958 "USD" 1.0 72.02 285506 1 2017-10-25 2017-10-26 "George Tooth" "Male" "Australia" 30 "Online store" "Contoso 512MB MP3 Player E51 S⦠"Silver" "Contoso" "Audio" "MP4&MP3" 1 11.691 11.691 5.958 "AUD" 1.2967 11.69 311002 2 2018-07-07 2018-07-12 "Caleb Greene" "Male" "Australia" 59 "Online store" "Contoso 512MB MP3 Player E51 S⦠"Silver" "Contoso" "Audio" "MP4&MP3" 6 12.99 12.99 6.62 "AUD" 1.3484 77.94 366307 2 2020-01-11 2020-01-11 "Isaac Siddins" "Male" "Australia" 25 "Contoso Store Western Australi⦠"Contoso 512MB MP3 Player E51 B⦠"Blue" "Contoso" "Audio" "MP4&MP3" 4 12.99 12.99 6.62 "AUD" 1.4545 51.96 325708 3 2018-12-01 2018-12-02 "Mike McQueen" "Male" "United States" 56 "Online store" "Contoso 512MB MP3 Player E51 B⦠"Blue" "Contoso" "Audio" "MP4&MP3" 2 12.99 11.5611 6.62 "USD" 1.0 23.12
over computes an aggregation per group but keeps one value per row, so the result has as
many rows as the frame:
π Nim π Python
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) Category Subcategory Sales Amt per Cat str str f64 "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
sales_by_cat = df.select(
'Category',
'Subcategory',
pl.col('Sales Amount').sum().over('Category').alias('Sales Amt per Cat')
)
sales_by_cat.head()
shape: (5, 3) Category Subcategory Sales Amt per Cat str str f64 "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
π Nim π Python
nbShow salesByCat.filter(col.Category == "Audio" ).unique(maintainOrder = true ).head()
shape: (3, 3) Category Subcategory Sales Amt per Cat str str f64 "Audio" "MP4&MP3" 238355.95 "Audio" "Recording Pen" 238355.95 "Audio" "Bluetooth Headphones" 238355.95
sales_by_cat.filter(pl.col('Category')=='Audio').unique(maintain_order=True).head()
shape: (3, 3) Category Subcategory Sales Amt per Cat str str f64 "Audio" "MP4&MP3" 238355.95 "Audio" "Recording Pen" 238355.95 "Audio" "Bluetooth Headphones" 238355.95
π Nim π Python
echo (df.shape, salesByCat.shape)
((13915, 21), (13915, 3))
df.shape, sales_by_cat.shape((13915, 21), (13915, 3))
Windows over two columns:
π Nim π Python
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) Category Brand Subcategory Avg Sales per Cat and Brand str str str f64 "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
(
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)
)
shape: (10, 4) Category Brand Subcategory Avg Sales per Cat and Brand str str str f64 "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
π»ββοΈ Nanuq
The book sorts by Brand only, which leaves the order within a brand open; both tabs sort
by subcategory as well.
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()
On GitHub: book/polars-cookbook/transformations.nim