Continuing expressions
The previous chapter introduced expressions; this one goes through the many methods an expression has, grouped by what they do to the shape of a column.
Types of operations
Example A: element-wise operations
An element-wise operation computes one value for each value: the result has as many rows as the input.
import std/math
import nanuq
let penguins = readCsv("data/definitive-guide/penguins.csv", nullValues = ["NA"]).select(
col.species, col.island, col.sex, col.year,
(col.body_mass_g / 1000).alias("mass"))
nbShow penguins.withColumns(
col.mass.sqrt.alias("mass_sqrt"),
col.mass.exp.alias("mass_exp"))
| species | island | sex | year | mass | mass_sqrt | mass_exp |
|---|---|---|---|---|---|---|
| str | str | str | i64 | f64 | f64 | f64 |
| "Adelie" | "Torgersen" | "male" | 2007 | 3.75 | 1.936492 | 42.521082 |
| "Adelie" | "Torgersen" | "female" | 2007 | 3.8 | 1.949359 | 44.701184 |
| "Adelie" | "Torgersen" | "female" | 2007 | 3.25 | 1.802776 | 25.79034 |
| "Adelie" | "Torgersen" | null | 2007 | null | null | null |
| "Adelie" | "Torgersen" | "female" | 2007 | 3.45 | 1.857418 | 31.500392 |
| … | … | … | … | … | … | … |
| "Chinstrap" | "Dream" | "male" | 2009 | 4.0 | 2.0 | 54.59815 |
| "Chinstrap" | "Dream" | "female" | 2009 | 3.4 | 1.843909 | 29.9641 |
| "Chinstrap" | "Dream" | "male" | 2009 | 3.775 | 1.942936 | 43.597508 |
| "Chinstrap" | "Dream" | "male" | 2009 | 4.1 | 2.024846 | 60.340288 |
| "Chinstrap" | "Dream" | "female" | 2009 | 3.775 | 1.942936 | 43.597508 |
import math
import polars as pl
penguins = pl.read_csv("data/definitive-guide/penguins.csv", null_values="NA").select(
"species",
"island",
"sex",
"year",
mass=pl.col("body_mass_g") / 1000,
)
penguins.with_columns(
mass_sqrt=pl.col("mass").sqrt(),
mass_exp=pl.col("mass").exp(),
)| species | island | sex | year | mass | mass_sqrt | mass_exp |
|---|---|---|---|---|---|---|
| str | str | str | i64 | f64 | f64 | f64 |
| "Adelie" | "Torgersen" | "male" | 2007 | 3.75 | 1.936492 | 42.521082 |
| "Adelie" | "Torgersen" | "female" | 2007 | 3.8 | 1.949359 | 44.701184 |
| "Adelie" | "Torgersen" | "female" | 2007 | 3.25 | 1.802776 | 25.79034 |
| "Adelie" | "Torgersen" | null | 2007 | null | null | null |
| "Adelie" | "Torgersen" | "female" | 2007 | 3.45 | 1.857418 | 31.500392 |
| … | … | … | … | … | … | … |
| "Chinstrap" | "Dream" | "male" | 2009 | 4.0 | 2.0 | 54.59815 |
| "Chinstrap" | "Dream" | "female" | 2009 | 3.4 | 1.843909 | 29.9641 |
| "Chinstrap" | "Dream" | "male" | 2009 | 3.775 | 1.942936 | 43.597508 |
| "Chinstrap" | "Dream" | "male" | 2009 | 4.1 | 2.024846 | 60.340288 |
| "Chinstrap" | "Dream" | "female" | 2009 | 3.775 | 1.942936 | 43.597508 |
Example B: operations that summarize to one
An aggregation reduces a column to one value:
nbShow penguins.select(col.mass.mean, col.island.first)
| mass | island |
|---|---|
| f64 | str |
| 4.201754 | "Torgersen" |
penguins.select(pl.col("mass").mean(), pl.col("island").first())| mass | island |
|---|---|
| f64 | str |
| 4.201754 | "Torgersen" |
Example C: operations that summarize to one or more
Some operations return a number of values that depends on the data, such as the distinct values:
nbShow penguins.select(col.island.unique)
| island |
|---|
| str |
| "Torgersen" |
| "Biscoe" |
| "Dream" |
penguins.select(pl.col("island").unique())| island |
|---|
| str |
| "Dream" |
| "Biscoe" |
| "Torgersen" |
Example D: operations that extend
A few operations make a column longer: here each species is repeated 3,000 times, as a
list per row that explode turns into rows, and extend_constant adds one more value.
nbShow penguins.select(
col.species
.unique(maintainOrder = true)
.repeatBy(3000)
.explode
.extendConstant("Saiyan", n = 1))
| species |
|---|
| str |
| "Adelie" |
| "Adelie" |
| "Adelie" |
| "Adelie" |
| "Adelie" |
| … |
| "Chinstrap" |
| "Chinstrap" |
| "Chinstrap" |
| "Chinstrap" |
| "Saiyan" |
penguins.select(
pl.col("species")
.unique(maintain_order=True)
.repeat_by(3000)
.explode()
.extend_constant("Saiyan", n=1)
)| species |
|---|
| str |
| "Adelie" |
| "Adelie" |
| "Adelie" |
| "Adelie" |
| "Adelie" |
| … |
| "Chinstrap" |
| "Chinstrap" |
| "Chinstrap" |
| "Chinstrap" |
| "Saiyan" |
Element-wise operations
Operations that perform mathematical transformations
nbShow newDataFrame(series("x", [-2.0, 0.0, 0.5, 1.0, E, 1000.0])).withColumns(
col.x.abs.alias("abs"),
col.x.exp.alias("exp"),
col.x.log(2).alias("log2"),
col.x.log10.alias("log10"),
col.x.log1p.alias("log1p"),
col.x.sign.alias("sign"),
col.x.sqrt.alias("sqrt"))
| x | abs | exp | log2 | log10 | log1p | sign | sqrt |
|---|---|---|---|---|---|---|---|
| f64 | f64 | f64 | f64 | f64 | f64 | f64 | f64 |
| -2.0 | 2.0 | 0.135335 | NaN | NaN | NaN | -1.0 | NaN |
| 0.0 | 0.0 | 1.0 | -inf | -inf | 0.0 | 0.0 | 0.0 |
| 0.5 | 0.5 | 1.648721 | -1.0 | -0.30103 | 0.405465 | 1.0 | 0.707107 |
| 1.0 | 1.0 | 2.718282 | 0.0 | 0.0 | 0.693147 | 1.0 | 1.0 |
| 2.718282 | 2.718282 | 15.154262 | 1.442695 | 0.434294 | 1.313262 | 1.0 | 1.648721 |
| 1000.0 | 1000.0 | inf | 9.965784 | 3.0 | 6.908755 | 1.0 | 31.622777 |
(
pl.DataFrame({"x": [-2.0, 0.0, 0.5, 1.0, math.e, 1000.0]}).with_columns(
abs=pl.col("x").abs(),
exp=pl.col("x").exp(),
log2=pl.col("x").log(2),
log10=pl.col("x").log10(),
log1p=pl.col("x").log1p(),
sign=pl.col("x").sign(),
sqrt=pl.col("x").sqrt(),
)
)| x | abs | exp | log2 | log10 | log1p | sign | sqrt |
|---|---|---|---|---|---|---|---|
| f64 | f64 | f64 | f64 | f64 | f64 | f64 | f64 |
| -2.0 | 2.0 | 0.135335 | NaN | NaN | NaN | -1.0 | NaN |
| 0.0 | 0.0 | 1.0 | -inf | -inf | 0.0 | 0.0 | 0.0 |
| 0.5 | 0.5 | 1.648721 | -1.0 | -0.30103 | 0.405465 | 1.0 | 0.707107 |
| 1.0 | 1.0 | 2.718282 | 0.0 | 0.0 | 0.693147 | 1.0 | 1.0 |
| 2.718282 | 2.718282 | 15.154262 | 1.442695 | 0.434294 | 1.313262 | 1.0 | 1.648721 |
| 1000.0 | 1000.0 | inf | 9.965784 | 3.0 | 6.908755 | 1.0 | 31.622777 |
Operations related to trigonometry
The trigonometric functions work in radians; degrees and radians convert.
nbShow newDataFrame(
series("x", [-PI, 0.0, 1.0, PI, 2 * PI, 90.0, 180.0, 360.0])
).withColumns(
col.x.arccos.alias("arccos"),
col.x.cos.alias("cos"),
col.x.degrees.alias("degrees"),
col.x.radians.alias("radians"),
col.x.sin.alias("sin"))
| x | arccos | cos | degrees | radians | sin |
|---|---|---|---|---|---|
| f64 | f64 | f64 | f64 | f64 | f64 |
| -3.141593 | NaN | -1.0 | -180.0 | -0.054831 | -1.2246e-16 |
| 0.0 | 1.570796 | 1.0 | 0.0 | 0.0 | 0.0 |
| 1.0 | 0.0 | 0.540302 | 57.29578 | 0.017453 | 0.841471 |
| 3.141593 | NaN | -1.0 | 180.0 | 0.054831 | 1.2246e-16 |
| 6.283185 | NaN | 1.0 | 360.0 | 0.109662 | -2.4493e-16 |
| 90.0 | NaN | -0.448074 | 5156.620156 | 1.570796 | 0.893997 |
| 180.0 | NaN | -0.59846 | 10313.240312 | 3.141593 | -0.801153 |
| 360.0 | NaN | -0.283691 | 20626.480625 | 6.283185 | 0.958916 |
(
pl.DataFrame(
{"x": [-math.pi, 0.0, 1.0, math.pi, 2 * math.pi, 90.0, 180.0, 360.0]}
).with_columns(
arccos=pl.col("x").arccos(),
cos=pl.col("x").cos(),
degrees=pl.col("x").degrees(),
radians=pl.col("x").radians(),
sin=pl.col("x").sin(),
)
)| x | arccos | cos | degrees | radians | sin |
|---|---|---|---|---|---|
| f64 | f64 | f64 | f64 | f64 | f64 |
| -3.141593 | NaN | -1.0 | -180.0 | -0.054831 | -1.2246e-16 |
| 0.0 | 1.570796 | 1.0 | 0.0 | 0.0 | 0.0 |
| 1.0 | 0.0 | 0.540302 | 57.29578 | 0.017453 | 0.841471 |
| 3.141593 | NaN | -1.0 | 180.0 | 0.054831 | 1.2246e-16 |
| 6.283185 | NaN | 1.0 | 360.0 | 0.109662 | -2.4493e-16 |
| 90.0 | NaN | -0.448074 | 5156.620156 | 1.570796 | 0.893997 |
| 180.0 | NaN | -0.59846 | 10313.240312 | 3.141593 | -0.801153 |
| 360.0 | NaN | -0.283691 | 20626.480625 | 6.283185 | 0.958916 |
Operations that round and categorize
cut puts each value in a bin between fixed breaks, qcut between quantiles of the data.
nbShow newDataFrame(
series("x", [-6.0, -0.5, 0.0, 0.5, PI, 9.9, 9.99, 9.999])
).withColumns(
col.x.ceil.alias("ceil"),
col.x.clip(-1, 1).alias("clip"),
col.x.cut([-1.0, 1.0], labels = ["bad", "neutral", "good"]).alias("cut"),
col.x.floor.alias("floor"),
col.x.qcut([0.5], labels = ["below median", "above median"]).alias("qcut"),
col.x.round(2).alias("round2"),
col.x.round(0).alias("round0"))
| x | ceil | clip | cut | floor | qcut | round2 | round0 |
|---|---|---|---|---|---|---|---|
| f64 | f64 | f64 | enum | f64 | cat | f64 | f64 |
| -6.0 | -6.0 | -1.0 | "bad" | -6.0 | "below median" | -6.0 | -6.0 |
| -0.5 | -0.0 | -0.5 | "neutral" | -1.0 | "below median" | -0.5 | -0.0 |
| 0.0 | 0.0 | 0.0 | "neutral" | 0.0 | "below median" | 0.0 | 0.0 |
| 0.5 | 1.0 | 0.5 | "neutral" | 0.0 | "below median" | 0.5 | 0.0 |
| 3.141593 | 4.0 | 1.0 | "good" | 3.0 | "above median" | 3.14 | 3.0 |
| 9.9 | 10.0 | 1.0 | "good" | 9.0 | "above median" | 9.9 | 10.0 |
| 9.99 | 10.0 | 1.0 | "good" | 9.0 | "above median" | 9.99 | 10.0 |
| 9.999 | 10.0 | 1.0 | "good" | 9.0 | "above median" | 10.0 | 10.0 |
(
pl.DataFrame(
{"x": [-6.0, -0.5, 0.0, 0.5, math.pi, 9.9, 9.99, 9.999]}
).with_columns(
ceil=pl.col("x").ceil(),
clip=pl.col("x").clip(-1, 1),
cut=pl.col("x").cut([-1, 1], labels=["bad", "neutral", "good"]),
floor=pl.col("x").floor(),
qcut=pl.col("x").qcut([0.5], labels=["below median", "above median"]),
round2=pl.col("x").round(2),
round0=pl.col("x").round(0),
)
)| x | ceil | clip | cut | floor | qcut | round2 | round0 |
|---|---|---|---|---|---|---|---|
| f64 | f64 | f64 | enum | f64 | cat | f64 | f64 |
| -6.0 | -6.0 | -1.0 | "bad" | -6.0 | "below median" | -6.0 | -6.0 |
| -0.5 | -0.0 | -0.5 | "neutral" | -1.0 | "below median" | -0.5 | -0.0 |
| 0.0 | 0.0 | 0.0 | "neutral" | 0.0 | "below median" | 0.0 | 0.0 |
| 0.5 | 1.0 | 0.5 | "neutral" | 0.0 | "below median" | 0.5 | 0.0 |
| 3.141593 | 4.0 | 1.0 | "good" | 3.0 | "above median" | 3.14 | 3.0 |
| 9.9 | 10.0 | 1.0 | "good" | 9.0 | "above median" | 9.9 | 10.0 |
| 9.99 | 10.0 | 1.0 | "good" | 9.0 | "above median" | 9.99 | 10.0 |
| 9.999 | 10.0 | 1.0 | "good" | 9.0 | "above median" | 10.0 | 10.0 |
Operations for missing or infinite values
A float column can hold missing values (null) and the special values NaN and infinity,
and each has its own tests and fills:
let xs = newDataFrame:
x: [42.0, NaN, nil, Inf, -Inf]
nbShow xs.withColumns(
col.x.fillNan(999).alias("fill_nan"),
col.x.fillNull(0).alias("fill_null"),
col.x.isFinite.alias("is_finite"),
col.x.isInfinite.alias("is_infinite"),
col.x.isNan.alias("is_nan"),
col.x.isNull.alias("is_null"))
| x | fill_nan | fill_null | is_finite | is_infinite | is_nan | is_null |
|---|---|---|---|---|---|---|
| f64 | f64 | f64 | bool | bool | bool | bool |
| 42.0 | 42.0 | 42.0 | true | false | false | false |
| NaN | 999.0 | NaN | false | false | true | false |
| null | null | 0.0 | null | null | null | true |
| inf | inf | inf | false | true | false | false |
| -inf | -inf | -inf | false | true | false | false |
x = [42.0, math.nan, None, math.inf, -math.inf]
(
pl.DataFrame({"x": x}).with_columns(
fill_nan=pl.col("x").fill_nan(999),
fill_null=pl.col("x").fill_null(0),
is_finite=pl.col("x").is_finite(),
is_infinite=pl.col("x").is_infinite(),
is_nan=pl.col("x").is_nan(),
is_null=pl.col("x").is_null(),
)
)| x | fill_nan | fill_null | is_finite | is_infinite | is_nan | is_null |
|---|---|---|---|---|---|---|
| f64 | f64 | f64 | bool | bool | bool | bool |
| 42.0 | 42.0 | 42.0 | true | false | false | false |
| NaN | 999.0 | NaN | false | false | true | false |
| null | null | 0.0 | null | null | null | true |
| inf | inf | inf | false | true | false | false |
| -inf | -inf | -inf | false | true | false | false |
To treat NaN and null alike, combine them:
nbShow xs.withColumns(
col.x.fillNan(0).fillNull(0).alias("fill_both"),
(col.x.isNan or col.x.isNull).alias("is_either"))
| x | fill_both | is_either |
|---|---|---|
| f64 | f64 | bool |
| 42.0 | 42.0 | false |
| NaN | 0.0 | true |
| null | 0.0 | true |
| inf | inf | false |
| -inf | -inf | false |
(
pl.DataFrame({"x": x}).with_columns(
fill_both=pl.col("x").fill_nan(0).fill_null(0),
is_either=(pl.col("x").is_nan() | pl.col("x").is_null()),
)
)| x | fill_both | is_either |
|---|---|---|
| f64 | f64 | bool |
| 42.0 | 42.0 | false |
| NaN | 0.0 | true |
| null | 0.0 | true |
| inf | inf | false |
| -inf | -inf | false |
Other operations
replace maps some values to others and leaves the rest alone:
nbShow newDataFrame(series("x", ["here", "there", "their", "they're"])).withColumns(
col.x.repeatBy(3).alias("repeat_by"),
col.x.replace({"here": "there", "they're": "they are"}).alias("replace"))
| x | repeat_by | replace |
|---|---|---|
| str | list[str] | str |
| "here" | ["here", "here", "here"] | "there" |
| "there" | ["there", "there", "there"] | "there" |
| "their" | ["their", "their", "their"] | "their" |
| "they're" | ["they're", "they're", "they're"] | "they are" |
(
pl.DataFrame({"x": ["here", "there", "their", "they're"]}).with_columns(
repeat_by=pl.col("x").repeat_by(3),
replace=pl.col("x").replace(
{
"here": "there",
"they're": "they are",
}
),
)
)| x | repeat_by | replace |
|---|---|---|
| str | list[str] | str |
| "here" | ["here", "here", "here"] | "there" |
| "there" | ["there", "there", "there"] | "there" |
| "their" | ["their", "their", "their"] | "their" |
| "they're" | ["they're", "they're", "they're"] | "they are" |
Nonreducing series-wise operations
These keep the length of the column, but each result depends on other values of the column, not only on its own.
Operations that accumulate
nbShow newDataFrame(
series("x", [some(0.0), some(1.0), some(2.0), none(float), some(2.0), some(NaN),
some(-1.0), some(2.0)])
).withColumns(
col.x.cumCount.alias("cum_count"),
col.x.cumMax.alias("cum_max"),
col.x.cumMin.alias("cum_min"),
col.x.cumProd(reverse = true).alias("cum_prod"),
col.x.cumSum.alias("cum_sum"),
col.x.diff.alias("diff"),
col.x.pctChange.alias("pct_change"))
| x | cum_count | cum_max | cum_min | cum_prod | cum_sum | diff | pct_change |
|---|---|---|---|---|---|---|---|
| f64 | u32 | f64 | f64 | f64 | f64 | f64 | f64 |
| 0.0 | 1 | 0.0 | 0.0 | NaN | 0.0 | null | null |
| 1.0 | 2 | 1.0 | 0.0 | NaN | 1.0 | 1.0 | inf |
| 2.0 | 3 | 2.0 | 0.0 | NaN | 3.0 | 1.0 | 1.0 |
| null | 3 | null | null | null | null | null | null |
| 2.0 | 4 | 2.0 | 0.0 | NaN | 5.0 | null | null |
| NaN | 5 | 2.0 | 0.0 | NaN | NaN | NaN | NaN |
| -1.0 | 6 | 2.0 | -1.0 | -2.0 | NaN | NaN | NaN |
| 2.0 | 7 | 2.0 | -1.0 | 2.0 | NaN | 3.0 | -3.0 |
import numpy as np
(
pl.DataFrame(
{"x": [0.0, 1.0, 2.0, None, 2.0, np.nan, -1.0, 2.0]}
).with_columns(
cum_count=pl.col("x").cum_count(),
cum_max=pl.col("x").cum_max(),
cum_min=pl.col("x").cum_min(),
cum_prod=pl.col("x").cum_prod(reverse=True),
cum_sum=pl.col("x").cum_sum(),
diff=pl.col("x").diff(),
pct_change=pl.col("x").pct_change(),
)
)| x | cum_count | cum_max | cum_min | cum_prod | cum_sum | diff | pct_change |
|---|---|---|---|---|---|---|---|
| f64 | u32 | f64 | f64 | f64 | f64 | f64 | f64 |
| 0.0 | 1 | 0.0 | 0.0 | NaN | 0.0 | null | null |
| 1.0 | 2 | 1.0 | 0.0 | NaN | 1.0 | 1.0 | inf |
| 2.0 | 3 | 2.0 | 0.0 | NaN | 3.0 | 1.0 | 1.0 |
| null | 3 | null | null | null | null | null | null |
| 2.0 | 4 | 2.0 | 0.0 | NaN | 5.0 | null | null |
| NaN | 5 | 2.0 | 0.0 | NaN | NaN | NaN | NaN |
| -1.0 | 6 | 2.0 | -1.0 | -2.0 | NaN | NaN | NaN |
| 2.0 | 7 | 2.0 | -1.0 | 2.0 | NaN | 3.0 | -3.0 |
Operations that fill and shift
Missing values can be filled from their neighbours, or interpolated; shift moves the
values down (or up, with a negative number).
nbShow newDataFrame(
series("x", [some(-1.0), some(0.0), some(1.0), none(float), none(float), some(3.0),
some(4.0), some(NaN), some(6.0)])
).withColumns(
col.x.backwardFill.alias("backward_fill"),
col.x.forwardFill(limit = 1).alias("forward_fill"),
col.x.interpolate(how = InterpolationMethod.Linear).alias("interp1"),
col.x.interpolate(how = InterpolationMethod.Nearest).alias("interp2"),
col.x.shift(1).alias("shift1"),
col.x.shift(-2).alias("shift2"))
| x | backward_fill | forward_fill | interp1 | interp2 | shift1 | shift2 |
|---|---|---|---|---|---|---|
| f64 | f64 | f64 | f64 | f64 | f64 | f64 |
| -1.0 | -1.0 | -1.0 | -1.0 | -1.0 | null | 1.0 |
| 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | -1.0 | null |
| 1.0 | 1.0 | 1.0 | 1.0 | 1.0 | 0.0 | null |
| null | 3.0 | 1.0 | 1.666667 | 1.0 | 1.0 | 3.0 |
| null | 3.0 | null | 2.333333 | 3.0 | null | 4.0 |
| 3.0 | 3.0 | 3.0 | 3.0 | 3.0 | null | NaN |
| 4.0 | 4.0 | 4.0 | 4.0 | 4.0 | 3.0 | 6.0 |
| NaN | NaN | NaN | NaN | NaN | 4.0 | null |
| 6.0 | 6.0 | 6.0 | 6.0 | 6.0 | NaN | null |
(
pl.DataFrame(
{"x": [-1.0, 0.0, 1.0, None, None, 3.0, 4.0, math.nan, 6.0]}
).with_columns(
backward_fill=pl.col("x").backward_fill(),
forward_fill=pl.col("x").forward_fill(limit=1),
interp1=pl.col("x").interpolate(method="linear"),
interp2=pl.col("x").interpolate(method="nearest"),
shift1=pl.col("x").shift(1),
shift2=pl.col("x").shift(-2),
)
)| x | backward_fill | forward_fill | interp1 | interp2 | shift1 | shift2 |
|---|---|---|---|---|---|---|
| f64 | f64 | f64 | f64 | f64 | f64 | f64 |
| -1.0 | -1.0 | -1.0 | -1.0 | -1.0 | null | 1.0 |
| 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | -1.0 | null |
| 1.0 | 1.0 | 1.0 | 1.0 | 1.0 | 0.0 | null |
| null | 3.0 | 1.0 | 1.666667 | 1.0 | 1.0 | 3.0 |
| null | 3.0 | null | 2.333333 | 3.0 | null | 4.0 |
| 3.0 | 3.0 | 3.0 | 3.0 | 3.0 | null | NaN |
| 4.0 | 4.0 | 4.0 | 4.0 | 4.0 | 3.0 | 6.0 |
| NaN | NaN | NaN | NaN | NaN | 4.0 | null |
| 6.0 | 6.0 | 6.0 | 6.0 | 6.0 | NaN | null |
Operations related to duplicate values
nbShow newDataFrame(series("x", ["A", "C", "D", "C"])).withColumns(
col.x.isDuplicated.alias("is_duplicated"),
col.x.isFirstDistinct.alias("is_first_distinct"),
col.x.isLastDistinct.alias("is_last_distinct"),
col.x.isUnique.alias("is_unique"))
| x | is_duplicated | is_first_distinct | is_last_distinct | is_unique |
|---|---|---|---|---|
| str | bool | bool | bool | bool |
| "A" | false | true | true | true |
| "C" | true | true | false | false |
| "D" | false | true | true | true |
| "C" | true | false | true | false |
(
pl.DataFrame({"x": ["A", "C", "D", "C"]}).with_columns(
is_duplicated=pl.col("x").is_duplicated(),
is_first_distinct=pl.col("x").is_first_distinct(),
is_last_distinct=pl.col("x").is_last_distinct(),
is_unique=pl.col("x").is_unique(),
)
)| x | is_duplicated | is_first_distinct | is_last_distinct | is_unique |
|---|---|---|---|---|
| str | bool | bool | bool | bool |
| "A" | false | true | true | true |
| "C" | true | true | false | false |
| "D" | false | true | true | true |
| "C" | true | false | true | false |
Operations that compute rolling statistics
A rolling statistic looks at a window of neighbouring values; an exponentially weighted mean (EWM) weighs all earlier values, the recent ones most. On NVIDIA's closing prices in 2023:
let stock = readCsv("data/definitive-guide/nvda_2023.csv", tryParseDates = true)
.select(col.date, col.close)
.withColumns(
col.close.ewmMean(com = 7, ignoreNulls = true).alias("ewm_mean"),
col.close.rollingMean(windowSize = 7).alias("rolling_mean"),
col.close.rollingMin(windowSize = 7).alias("rolling_min"))
nbShow stock
| date | close | ewm_mean | rolling_mean | rolling_min |
|---|---|---|---|---|
| date | f64 | f64 | f64 | f64 |
| 2023-01-03 | 143.149994 | 143.149994 | null | null |
| 2023-01-04 | 147.490005 | 145.464667 | null | null |
| 2023-01-05 | 142.649994 | 144.398755 | null | null |
| 2023-01-06 | 148.589996 | 145.664782 | null | null |
| 2023-01-09 | 156.279999 | 148.388917 | null | null |
| … | … | … | … | … |
| 2023-06-26 | 406.320007 | 407.54911 | 425.805716 | 406.320007 |
| 2023-06-27 | 418.76001 | 408.950473 | 424.695718 | 406.320007 |
| 2023-06-28 | 411.170013 | 409.227915 | 422.445718 | 406.320007 |
| 2023-06-29 | 408.220001 | 409.101926 | 418.180006 | 406.320007 |
| 2023-06-30 | 423.019989 | 410.841684 | 417.118574 | 406.320007 |
stock = (
pl.read_csv("data/definitive-guide/nvda_2023.csv", try_parse_dates=True)
.select("date", "close")
.with_columns(
ewm_mean=pl.col("close").ewm_mean(com=7, ignore_nulls=True),
rolling_mean=pl.col("close").rolling_mean(window_size=7),
rolling_min=pl.col("close").rolling_min(window_size=7),
)
)
stock| date | close | ewm_mean | rolling_mean | rolling_min |
|---|---|---|---|---|
| date | f64 | f64 | f64 | f64 |
| 2023-01-03 | 143.149994 | 143.149994 | null | null |
| 2023-01-04 | 147.490005 | 145.464667 | null | null |
| 2023-01-05 | 142.649994 | 144.398755 | null | null |
| 2023-01-06 | 148.589996 | 145.664782 | null | null |
| 2023-01-09 | 156.279999 | 148.388917 | null | null |
| … | … | … | … | … |
| 2023-06-26 | 406.320007 | 407.54911 | 425.805716 | 406.320007 |
| 2023-06-27 | 418.76001 | 408.950473 | 424.695718 | 406.320007 |
| 2023-06-28 | 411.170013 | 409.227915 | 422.445718 | 406.320007 |
| 2023-06-29 | 408.220001 | 409.101926 | 418.180006 | 406.320007 |
| 2023-06-30 | 423.019989 | 410.841684 | 417.118574 | 406.320007 |
Operations that sort
nbShow newDataFrame(
series("x", [some(1), some(3), none(int), some(3), some(7)]),
series("y", ["D", "I", "S", "C", "O"])
).withColumns(
col.x.argSort.alias("arg_sort"),
col.x.shuffle(seed = 7).alias("shuffle"),
col.x.sort(nullsLast = true).alias("sort"),
col.x.sortBy("y").alias("sort_by"),
col.x.reverse.alias("reverse"),
col.x.rank.alias("rank"))
| x | y | arg_sort | shuffle | sort | sort_by | reverse | rank |
|---|---|---|---|---|---|---|---|
| i64 | str | u32 | i64 | i64 | i64 | i64 | f64 |
| 1 | "D" | 2 | 7 | 1 | 3 | 7 | 1.0 |
| 3 | "I" | 0 | 3 | 3 | 1 | 3 | 2.5 |
| null | "S" | 1 | 3 | 3 | 3 | null | null |
| 3 | "C" | 3 | null | 7 | 7 | 3 | 2.5 |
| 7 | "O" | 4 | 1 | null | null | 1 | 4.0 |
(
pl.DataFrame(
{
"x": [1, 3, None, 3, 7],
"y": ["D", "I", "S", "C", "O"],
}
).with_columns(
arg_sort=pl.col("x").arg_sort(),
shuffle=pl.col("x").shuffle(seed=7),
sort=pl.col("x").sort(nulls_last=True),
sort_by=pl.col("x").sort_by("y"),
reverse=pl.col("x").reverse(),
rank=pl.col("x").rank(),
)
)| x | y | arg_sort | shuffle | sort | sort_by | reverse | rank |
|---|---|---|---|---|---|---|---|
| i64 | str | u32 | i64 | i64 | i64 | i64 | f64 |
| 1 | "D" | 2 | 7 | 1 | 3 | 7 | 1.0 |
| 3 | "I" | 0 | 3 | 3 | 1 | 3 | 2.5 |
| null | "S" | 1 | 3 | 3 | 3 | null | null |
| 3 | "C" | 3 | null | 7 | 7 | 3 | 2.5 |
| 7 | "O" | 4 | 1 | null | null | 1 | 4.0 |
Other operations
rle_id numbers the runs of equal values:
nbShow newDataFrame(series("x", [33, 33, 27, 33, 60, 60, 60, 33, 60])).withColumns(
col.x.rleId.alias("rle_id"))
| x | rle_id |
|---|---|
| i64 | u32 |
| 33 | 0 |
| 33 | 0 |
| 27 | 1 |
| 33 | 2 |
| 60 | 3 |
| 60 | 3 |
| 60 | 3 |
| 33 | 4 |
| 60 | 5 |
(
pl.DataFrame({"x": [33, 33, 27, 33, 60, 60, 60, 33, 60]}).with_columns(
rle_id=pl.col("x").rle_id(),
)
)| x | rle_id |
|---|---|
| i64 | u32 |
| 33 | 0 |
| 33 | 0 |
| 27 | 1 |
| 33 | 2 |
| 60 | 3 |
| 60 | 3 |
| 60 | 3 |
| 33 | 4 |
| 60 | 5 |
Series-wise operations that summarize to one
An aggregation in with_columns is broadcast to every row; in a group-by it gives one
value per group.
nbShow newDataFrame(series("x", [1, 3, 3, 7])).withColumns(col.x.mean.alias("mean"))
| x | mean |
|---|---|
| i64 | f64 |
| 1 | 3.5 |
| 3 | 3.5 |
| 3 | 3.5 |
| 7 | 3.5 |
(
pl.DataFrame({"x": [1, 3, 3, 7]}).with_columns(
mean=pl.col("x").mean(),
)
)| x | mean |
|---|---|
| i64 | f64 |
| 1 | 3.5 |
| 3 | 3.5 |
| 3 | 3.5 |
| 7 | 3.5 |
nbShow newDataFrame(series("cluster", ["a", "a", "b", "b"]), series("x", [1, 3, 3, 7]))
.groupBy("cluster")
.agg(col.x.mean.alias("mean"))
| cluster | mean |
|---|---|
| str | f64 |
| "a" | 2.0 |
| "b" | 5.0 |
(
pl.DataFrame({"cluster": ["a", "a", "b", "b"], "x": [1, 3, 3, 7]})
.group_by("cluster")
.agg(
mean=pl.col("x").mean(),
)
)| cluster | mean |
|---|---|
| str | f64 |
| "b" | 5.0 |
| "a" | 2.0 |
Operations that are quantifiers
all is true when every value is, any when at least one is:
let bools = newDataFrame:
x: [true, false, false]
y: [true, true, true]
z: [false, false, false]
echo bools
nbShow bools.select(
all().all.name.suffix("_all"),
all().any.name.suffix("_any"))
| x_all | y_all | z_all | x_any | y_any | z_any |
|---|---|---|---|---|---|
| bool | bool | bool | bool | bool | bool |
| false | true | false | true | true | false |
shape: (3, 3) βββββββββ¬βββββββ¬ββββββββ β x β y β z β β --- β --- β --- β β bool β bool β bool β βββββββββͺβββββββͺββββββββ‘ β true β true β false β β false β true β false β β false β true β false β βββββββββ΄βββββββ΄ββββββββ
df = pl.DataFrame(
{
"x": [True, False, False],
"y": [True, True, True],
"z": [False, False, False],
}
)
print(df)
df.select(
pl.all().all().name.suffix("_all"),
pl.all().any().name.suffix("_any"),
)shape: (3, 3) βββββββββ¬βββββββ¬ββββββββ β x β y β z β β --- β --- β --- β β bool β bool β bool β βββββββββͺβββββββͺββββββββ‘ β true β true β false β β false β true β false β β false β true β false β βββββββββ΄βββββββ΄ββββββββ
| x_all | y_all | z_all | x_any | y_any | z_any |
|---|---|---|---|---|---|
| bool | bool | bool | bool | bool | bool |
| false | true | false | true | true | false |
Operations that compute statistics
nbShow penguins.select(
col.mass.max.alias("max"),
col.mass.mean.alias("mean"),
col.mass.quantile(0.95).alias("quantile"),
col.mass.skew.alias("skew"),
col.mass.std.alias("std"),
col.mass.sum.alias("sum"),
col.mass.var.alias("var"))
| max | mean | quantile | skew | std | sum | var |
|---|---|---|---|---|---|---|
| f64 | f64 | f64 | f64 | f64 | f64 | f64 |
| 6.3 | 4.201754 | 5.65 | 0.468264 | 0.801955 | 1437.0 | 0.643131 |
(
penguins.select(
max=pl.col("mass").max(),
mean=pl.col("mass").mean(),
quantile=pl.col("mass").quantile(quantile=0.95),
skew=pl.col("mass").skew(),
std=pl.col("mass").std(),
sum=pl.col("mass").sum(),
var=pl.col("mass").var(),
)
)| max | mean | quantile | skew | std | sum | var |
|---|---|---|---|---|---|---|
| f64 | f64 | f64 | f64 | f64 | f64 | f64 |
| 6.3 | 4.201754 | 5.65 | 0.468264 | 0.801955 | 1437.0 | 0.643131 |
Operations that count
1,729 random integers below 10,000, one of them made missing:
import std/sequtils
let dfInts = newDataFrame(series("x", toSeq(0 ..< 10_000)))
.sample(1_729, withReplacement = true, seed = 1729)
.withRowIndex()
.withColumns(`when`(col.index != 403).then(col.x).alias("x"))
nbShow dfInts.slice(400, 6)
| index | x |
|---|---|
| u32 | i64 |
| 400 | 5551 |
| 401 | 978 |
| 402 | 3450 |
| 403 | null |
| 404 | 8411 |
| 405 | 3448 |
df_ints = (
pl.DataFrame({"x": range(10_000)})
.sample(1_729, with_replacement=True, seed=1729)
.with_row_index()
.with_columns(x=pl.when(pl.col("index") != 403).then(pl.col("x")))
)
df_ints.slice(400, 6)| index | x |
|---|---|
| u32 | i64 |
| 400 | 5551 |
| 401 | 978 |
| 402 | 3450 |
| 403 | null |
| 404 | 8411 |
| 405 | 3448 |
nbShow dfInts.select(
col.x.approxNUnique.alias("approx_n_unique"),
col.x.count.alias("count"),
col.x.len.alias("len"),
col.x.nUnique.alias("n_unique"),
col.x.nullCount.alias("null_count"))
| approx_n_unique | count | len | n_unique | null_count |
|---|---|---|---|---|
| u32 | u32 | u32 | u32 | u32 |
| 1595 | 1728 | 1729 | 1588 | 1 |
df_ints.select(
approx_n_unique=pl.col("x").approx_n_unique(),
count=pl.col("x").count(),
len=pl.col("x").len(),
n_unique=pl.col("x").n_unique(),
null_count=pl.col("x").null_count(),
)| approx_n_unique | count | len | n_unique | null_count |
|---|---|---|---|---|
| u32 | u32 | u32 | u32 | u32 |
| 1595 | 1728 | 1729 | 1588 | 1 |
The book then times n_unique against approx_n_unique on ten million integers: the
approximation is several times faster. (Timings are left out of this book's builds.)
Other operations
nbShow dfInts.select(
col.x.argMin.alias("arg_min"),
col.x.first.alias("first"),
col.x.get(403).alias("get"),
col.x.implode.alias("implode"),
col.x.last.alias("last"),
col.x.upperBound.alias("upper_bound"))
| arg_min | first | get | implode | last | upper_bound |
|---|---|---|---|---|---|
| u32 | i64 | i64 | list[i64] | i64 | i64 |
| 287 | 3943 | null | [3943, 5730, β¦ 4825] | 4825 | 9223372036854775807 |
df_ints.select(
arg_min=pl.col("x").arg_min(),
first=pl.col("x").first(),
get=pl.col("x").get(403),
implode=pl.col("x").implode(),
last=pl.col("x").last(),
upper_bound=pl.col("x").upper_bound(),
)| arg_min | first | get | implode | last | upper_bound |
|---|---|---|---|---|---|
| u32 | i64 | i64 | list[i64] | i64 | i64 |
| 287 | 3943 | null | [3943, 5730, β¦ 4825] | 4825 | 9223372036854775807 |
Series-wise operations that summarize to one or more
Operations related to unique values
nbShow newDataFrame(series("x", ["A", "C", "D", "C"])).select(
col.x.argUnique.alias("arg_unique"),
col.x.unique(maintainOrder = true).alias("unique"),
col.x.uniqueCounts.alias("unique_counts"),
col.x.valueCounts(sort = true).alias("value_counts"))
| arg_unique | unique | unique_counts | value_counts |
|---|---|---|---|
| u32 | str | u32 | struct[2] |
| 0 | "A" | 1 | {"C",2} |
| 1 | "C" | 2 | {"A",1} |
| 2 | "D" | 1 | {"D",1} |
(
pl.DataFrame({"x": ["A", "C", "D", "C"]}).select(
arg_unique=pl.col("x").arg_unique(),
unique=pl.col("x").unique(maintain_order=True),
unique_counts=pl.col("x").unique_counts(),
value_counts=pl.col("x").value_counts(sort=True),
)
)| arg_unique | unique | unique_counts | value_counts |
|---|---|---|---|
| u32 | str | u32 | struct[2] |
| 0 | "A" | 1 | {"C",2} |
| 1 | "C" | 2 | {"A",1} |
| 2 | "D" | 1 | {"D",1} |
Operations that select
nbShow dfInts.select(
col.x.bottomK(7).alias("bottom_k"),
col.x.head(7).alias("head"),
col.x.slice(400, 7).alias("slice"),
col.x.gather([1, 1, 2, 3, 5, 8, 13]).alias("gather"),
col.x.gatherEvery(247).alias("gather_every"),
col.x.topK(7).alias("top_k"))
| bottom_k | head | slice | gather | gather_every | top_k |
|---|---|---|---|---|---|
| i64 | i64 | i64 | i64 | i64 | i64 |
| 33 | 3943 | 5551 | 5730 | 3943 | 9992 |
| 27 | 5730 | 978 | 5730 | 1072 | 9978 |
| 6 | 3890 | 3450 | 3890 | 5762 | 9964 |
| 11 | 5807 | null | 5807 | 1711 | 9962 |
| 9 | 7624 | 8411 | 8523 | 2482 | 9961 |
| 34 | 8523 | 3448 | 1179 | 3127 | 9952 |
| 39 | 794 | 1870 | 2526 | 9343 | 9943 |
df_ints.select(
bottom_k=pl.col("x").bottom_k(7),
head=pl.col("x").head(7),
slice=pl.col("x").slice(400, 7),
gather=pl.col("x").gather([1, 1, 2, 3, 5, 8, 13]),
gather_every=pl.col("x").gather_every(247),
top_k=pl.col("x").top_k(7),
)| bottom_k | head | slice | gather | gather_every | top_k |
|---|---|---|---|---|---|
| i64 | i64 | i64 | i64 | i64 | i64 |
| 33 | 3943 | 5551 | 5730 | 3943 | 9992 |
| 27 | 5730 | 978 | 5730 | 1072 | 9978 |
| 6 | 3890 | 3450 | 3890 | 5762 | 9964 |
| 11 | 5807 | null | 5807 | 1711 | 9962 |
| 9 | 7624 | 8411 | 8523 | 2482 | 9961 |
| 34 | 8523 | 3448 | 1179 | 3127 | 9952 |
| 39 | 794 | 1870 | 2526 | 9343 | 9943 |
Operations that drop missing values
nbShow newDataFrame(
series("x", [none(float), some(1.0), some(2.0), some(3.0), some(NaN)])
).select(
col.x.dropNans.alias("drop_nans"), col.x.dropNulls.alias("drop_nulls"))
| drop_nans | drop_nulls |
|---|---|
| f64 | f64 |
| null | 1.0 |
| 1.0 | 2.0 |
| 2.0 | 3.0 |
| 3.0 | NaN |
x = [None, 1.0, 2.0, 3.0, np.nan]
(
pl.DataFrame({"x": x}).select(
drop_nans=pl.col("x").drop_nans(), drop_nulls=pl.col("x").drop_nulls()
)
)| drop_nans | drop_nulls |
|---|---|
| f64 | f64 |
| null | 1.0 |
| 1.0 | 2.0 |
| 2.0 | 3.0 |
| 3.0 | NaN |
Other operations
mode gives the most common values (more than one when they tie):
let numbers = newDataFrame:
x: [33, 33, 27, 33, 60, 60, 60, 33, 60]
nbShow numbers.select((col.x >= 60).argTrue.alias("arg_true"))
| arg_true |
|---|
| u32 |
| 4 |
| 5 |
| 6 |
| 8 |
numbers = [33, 33, 27, 33, 60, 60, 60, 33, 60]
(
pl.DataFrame({"x": numbers}).select(
arg_true=(pl.col("x") >= 60).arg_true(),
)
)| arg_true |
|---|
| u32 |
| 4 |
| 5 |
| 6 |
| 8 |
nbShow numbers.select(col.x.mode.sort.alias("mode"))
| mode |
|---|
| i64 |
| 33 |
| 60 |
(
pl.DataFrame({"x": numbers}).select(
mode=pl.col("x").mode().sort(),
)
)| mode |
|---|
| i64 |
| 33 |
| 60 |
reshape turns the column into arrays, here three of three values:
nbShow numbers.select(col.x.reshape([3, 3]).alias("reshape"))
| reshape |
|---|
| array[i64, 3] |
| [33, 33, 27] |
| [33, 60, 60] |
| [60, 33, 60] |
(
pl.DataFrame({"x": numbers}).select(
reshape=pl.col("x").reshape((3, 3)),
)
)| reshape |
|---|
| array[i64, 3] |
| [33, 33, 27] |
| [33, 60, 60] |
| [60, 33, 60] |
rle gives the runs of equal values, as structs of a length and a value:
nbShow numbers.select(col.x.rle.alias("rle"))
| rle |
|---|
| struct[2] |
| {2,33} |
| {1,27} |
| {1,33} |
| {3,60} |
| {1,33} |
| {1,60} |
(
pl.DataFrame({"x": numbers}).select(
rle=pl.col("x").rle(),
)
)| rle |
|---|
| struct[2] |
| {2,33} |
| {1,27} |
| {1,33} |
| {3,60} |
| {1,33} |
| {1,60} |
search_sorted gives the position where a value would go in a sorted column:
nbShow numbers.select(col.x.sort.searchSorted(42).alias("rle"))
| rle |
|---|
| u32 |
| 5 |
(
pl.DataFrame({"x": numbers}).select(
rle=pl.col("x").sort().search_sorted(42),
)
)| rle |
|---|
| u32 |
| 5 |
nbShow newDataFrame(series("x", [@["a", "b"], @["c", "d"]]))
.select(col.x.explode.alias("explode"))
| explode |
|---|
| str |
| "a" |
| "b" |
| "c" |
| "d" |
(
pl.DataFrame(
{
"x": [["a", "b"], ["c", "d"]],
}
).select(explode=pl.col("x").explode())
)| explode |
|---|
| str |
| "a" |
| "b" |
| "c" |
| "d" |
import nanuqbook
bookInit()
nbText: "# Continuing expressions"
attribution definitiveGuide(8, "Continuing Expressions",
"Data is read from `data/definitive-guide/` (the NVIDIA prices are the book's " &
"`stock/nvda/2023.csv`). The book draws random numbers with numpy; here both sides draw " &
"them with Polars' seeded `sample`, or use the penguins, so that they get the same ones. " &
"Left out: `hash` and `sample` on an expression (their results depend on the Polars " &
"version), the timing cells and the plot.")
nbText: """
The previous chapter introduced expressions; this one goes through the many methods an
expression has, grouped by what they do to the shape of a column.
## Types of operations
### Example A: element-wise operations
An element-wise operation computes one value for each value: the result has as many rows
as the input.
"""
nanuq """
Python names new columns with keyword arguments (`mass=...`); Nim with `alias`.
"""
tabs """
import math
import polars as pl
penguins = pl.read_csv("data/definitive-guide/penguins.csv", null_values="NA").select(
"species",
"island",
"sex",
"year",
mass=pl.col("body_mass_g") / 1000,
)
penguins.with_columns(
mass_sqrt=pl.col("mass").sqrt(),
mass_exp=pl.col("mass").exp(),
)
""":
nbCode:
import std/math
import nanuq
let penguins = readCsv("data/definitive-guide/penguins.csv", nullValues = ["NA"]).select(
col.species, col.island, col.sex, col.year,
(col.body_mass_g / 1000).alias("mass"))
nbShow penguins.withColumns(
col.mass.sqrt.alias("mass_sqrt"),
col.mass.exp.alias("mass_exp"))
nbText: """
### Example B: operations that summarize to one
An aggregation reduces a column to one value:
"""
tabs """
penguins.select(pl.col("mass").mean(), pl.col("island").first())
""":
nbCode:
nbShow penguins.select(col.mass.mean, col.island.first)
nbText: """
### Example C: operations that summarize to one or more
Some operations return a number of values that depends on the data, such as the distinct
values:
"""
nanuq """
Without `maintain_order`, `unique` returns the values in any order; the book compares the
rows of both sides as a set.
"""
tabs """
penguins.select(pl.col("island").unique())
""":
nbCode:
nbShow penguins.select(col.island.unique)
nbText: """
### Example D: operations that extend
A few operations make a column longer: here each species is repeated 3,000 times, as a
list per row that `explode` turns into rows, and `extend_constant` adds one more value.
"""
nanuq """
The Python side adds `maintain_order=True` to `unique`, so that the 9,001 rows come in
the same order on both sides (only the first and last are shown).
"""
tabs """
penguins.select(
pl.col("species")
.unique(maintain_order=True)
.repeat_by(3000)
.explode()
.extend_constant("Saiyan", n=1)
)
""":
nbCode:
nbShow penguins.select(
col.species
.unique(maintainOrder = true)
.repeatBy(3000)
.explode
.extendConstant("Saiyan", n = 1))
nbText: """
## Element-wise operations
### Operations that perform mathematical transformations
"""
nanuq """
`log(2)` is the logarithm in base 2; `log` with no argument is the natural logarithm, as
in Python. The `math.e` of Python is `E` from std/math.
"""
tabs """
(
pl.DataFrame({"x": [-2.0, 0.0, 0.5, 1.0, math.e, 1000.0]}).with_columns(
abs=pl.col("x").abs(),
exp=pl.col("x").exp(),
log2=pl.col("x").log(2),
log10=pl.col("x").log10(),
log1p=pl.col("x").log1p(),
sign=pl.col("x").sign(),
sqrt=pl.col("x").sqrt(),
)
)
""":
nbCode:
nbShow newDataFrame(series("x", [-2.0, 0.0, 0.5, 1.0, E, 1000.0])).withColumns(
col.x.abs.alias("abs"),
col.x.exp.alias("exp"),
col.x.log(2).alias("log2"),
col.x.log10.alias("log10"),
col.x.log1p.alias("log1p"),
col.x.sign.alias("sign"),
col.x.sqrt.alias("sqrt"))
nbText: """
### Operations related to trigonometry
The trigonometric functions work in radians; `degrees` and `radians` convert.
"""
tabs """
(
pl.DataFrame(
{"x": [-math.pi, 0.0, 1.0, math.pi, 2 * math.pi, 90.0, 180.0, 360.0]}
).with_columns(
arccos=pl.col("x").arccos(),
cos=pl.col("x").cos(),
degrees=pl.col("x").degrees(),
radians=pl.col("x").radians(),
sin=pl.col("x").sin(),
)
)
""":
nbCode:
nbShow newDataFrame(
series("x", [-PI, 0.0, 1.0, PI, 2 * PI, 90.0, 180.0, 360.0])
).withColumns(
col.x.arccos.alias("arccos"),
col.x.cos.alias("cos"),
col.x.degrees.alias("degrees"),
col.x.radians.alias("radians"),
col.x.sin.alias("sin"))
nbText: """
### Operations that round and categorize
`cut` puts each value in a bin between fixed breaks, `qcut` between quantiles of the data.
"""
nanuq """
`clip(-1, 1)` takes both bounds; with one, name it: `clip(lowerBound = 0)`. `round` rounds
half to even by default, like Python Polars.
"""
tabs """
(
pl.DataFrame(
{"x": [-6.0, -0.5, 0.0, 0.5, math.pi, 9.9, 9.99, 9.999]}
).with_columns(
ceil=pl.col("x").ceil(),
clip=pl.col("x").clip(-1, 1),
cut=pl.col("x").cut([-1, 1], labels=["bad", "neutral", "good"]),
floor=pl.col("x").floor(),
qcut=pl.col("x").qcut([0.5], labels=["below median", "above median"]),
round2=pl.col("x").round(2),
round0=pl.col("x").round(0),
)
)
""":
nbCode:
nbShow newDataFrame(
series("x", [-6.0, -0.5, 0.0, 0.5, PI, 9.9, 9.99, 9.999])
).withColumns(
col.x.ceil.alias("ceil"),
col.x.clip(-1, 1).alias("clip"),
col.x.cut([-1.0, 1.0], labels = ["bad", "neutral", "good"]).alias("cut"),
col.x.floor.alias("floor"),
col.x.qcut([0.5], labels = ["below median", "above median"]).alias("qcut"),
col.x.round(2).alias("round2"),
col.x.round(0).alias("round0"))
nbText: """
### Operations for missing or infinite values
A float column can hold missing values (`null`) and the special values NaN and infinity,
and each has its own tests and fills:
"""
nanuq """
In Nim a missing value is `none(float)`, and NaN and infinity are `NaN` and `Inf`.
"""
tabs """
x = [42.0, math.nan, None, math.inf, -math.inf]
(
pl.DataFrame({"x": x}).with_columns(
fill_nan=pl.col("x").fill_nan(999),
fill_null=pl.col("x").fill_null(0),
is_finite=pl.col("x").is_finite(),
is_infinite=pl.col("x").is_infinite(),
is_nan=pl.col("x").is_nan(),
is_null=pl.col("x").is_null(),
)
)
""":
nbCode:
let xs = newDataFrame:
x: [42.0, NaN, nil, Inf, -Inf]
nbShow xs.withColumns(
col.x.fillNan(999).alias("fill_nan"),
col.x.fillNull(0).alias("fill_null"),
col.x.isFinite.alias("is_finite"),
col.x.isInfinite.alias("is_infinite"),
col.x.isNan.alias("is_nan"),
col.x.isNull.alias("is_null"))
nbText: "To treat NaN and null alike, combine them:"
tabs """
(
pl.DataFrame({"x": x}).with_columns(
fill_both=pl.col("x").fill_nan(0).fill_null(0),
is_either=(pl.col("x").is_nan() | pl.col("x").is_null()),
)
)
""":
nbCode:
nbShow xs.withColumns(
col.x.fillNan(0).fillNull(0).alias("fill_both"),
(col.x.isNan or col.x.isNull).alias("is_either"))
nbText: """
### Other operations
`replace` maps some values to others and leaves the rest alone:
"""
nanuq """
Nim writes the mapping of `replace` as `{"a": "b"}`. The book also shows
`hash(seed=1337)`, which Nanuq has (`col.x.hash(seed = 1337)`), but its values depend on
the Polars version, and Nanuq's Rust Polars is not the one inside Python Polars 2.1, so
that column is left out.
"""
tabs """
(
pl.DataFrame({"x": ["here", "there", "their", "they're"]}).with_columns(
repeat_by=pl.col("x").repeat_by(3),
replace=pl.col("x").replace(
{
"here": "there",
"they're": "they are",
}
),
)
)
""":
nbCode:
nbShow newDataFrame(series("x", ["here", "there", "their", "they're"])).withColumns(
col.x.repeatBy(3).alias("repeat_by"),
col.x.replace({"here": "there", "they're": "they are"}).alias("replace"))
nbText: """
## Nonreducing series-wise operations
These keep the length of the column, but each result depends on other values of the
column, not only on its own.
### Operations that accumulate
"""
tabs """
import numpy as np
(
pl.DataFrame(
{"x": [0.0, 1.0, 2.0, None, 2.0, np.nan, -1.0, 2.0]}
).with_columns(
cum_count=pl.col("x").cum_count(),
cum_max=pl.col("x").cum_max(),
cum_min=pl.col("x").cum_min(),
cum_prod=pl.col("x").cum_prod(reverse=True),
cum_sum=pl.col("x").cum_sum(),
diff=pl.col("x").diff(),
pct_change=pl.col("x").pct_change(),
)
)
""":
nbCode:
nbShow newDataFrame(
series("x", [some(0.0), some(1.0), some(2.0), none(float), some(2.0), some(NaN),
some(-1.0), some(2.0)])
).withColumns(
col.x.cumCount.alias("cum_count"),
col.x.cumMax.alias("cum_max"),
col.x.cumMin.alias("cum_min"),
col.x.cumProd(reverse = true).alias("cum_prod"),
col.x.cumSum.alias("cum_sum"),
col.x.diff.alias("diff"),
col.x.pctChange.alias("pct_change"))
nbText: """
### Operations that fill and shift
Missing values can be filled from their neighbours, or interpolated; `shift` moves the
values down (or up, with a negative number).
"""
nanuq """
Python's `method` is `how` in Nanuq (as for `rank` and `corr`), a value of the enum
`InterpolationMethod`: `Linear` or `Nearest`.
"""
tabs """
(
pl.DataFrame(
{"x": [-1.0, 0.0, 1.0, None, None, 3.0, 4.0, math.nan, 6.0]}
).with_columns(
backward_fill=pl.col("x").backward_fill(),
forward_fill=pl.col("x").forward_fill(limit=1),
interp1=pl.col("x").interpolate(method="linear"),
interp2=pl.col("x").interpolate(method="nearest"),
shift1=pl.col("x").shift(1),
shift2=pl.col("x").shift(-2),
)
)
""":
nbCode:
nbShow newDataFrame(
series("x", [some(-1.0), some(0.0), some(1.0), none(float), none(float), some(3.0),
some(4.0), some(NaN), some(6.0)])
).withColumns(
col.x.backwardFill.alias("backward_fill"),
col.x.forwardFill(limit = 1).alias("forward_fill"),
col.x.interpolate(how = InterpolationMethod.Linear).alias("interp1"),
col.x.interpolate(how = InterpolationMethod.Nearest).alias("interp2"),
col.x.shift(1).alias("shift1"),
col.x.shift(-2).alias("shift2"))
nbText: "### Operations related to duplicate values"
tabs """
(
pl.DataFrame({"x": ["A", "C", "D", "C"]}).with_columns(
is_duplicated=pl.col("x").is_duplicated(),
is_first_distinct=pl.col("x").is_first_distinct(),
is_last_distinct=pl.col("x").is_last_distinct(),
is_unique=pl.col("x").is_unique(),
)
)
""":
nbCode:
nbShow newDataFrame(series("x", ["A", "C", "D", "C"])).withColumns(
col.x.isDuplicated.alias("is_duplicated"),
col.x.isFirstDistinct.alias("is_first_distinct"),
col.x.isLastDistinct.alias("is_last_distinct"),
col.x.isUnique.alias("is_unique"))
nbText: """
### Operations that compute rolling statistics
A rolling statistic looks at a window of neighbouring values; an exponentially weighted
mean (EWM) weighs all earlier values, the recent ones most. On NVIDIA's closing prices in
2023:
"""
nanuq """
`ewmMean` takes the decay by name, as one of `com`, `span`, `halfLife` or `alpha`. The
book then plots the three series with plotnine; the plot is left out.
"""
tabs """
stock = (
pl.read_csv("data/definitive-guide/nvda_2023.csv", try_parse_dates=True)
.select("date", "close")
.with_columns(
ewm_mean=pl.col("close").ewm_mean(com=7, ignore_nulls=True),
rolling_mean=pl.col("close").rolling_mean(window_size=7),
rolling_min=pl.col("close").rolling_min(window_size=7),
)
)
stock
""":
nbCode:
let stock = readCsv("data/definitive-guide/nvda_2023.csv", tryParseDates = true)
.select(col.date, col.close)
.withColumns(
col.close.ewmMean(com = 7, ignoreNulls = true).alias("ewm_mean"),
col.close.rollingMean(windowSize = 7).alias("rolling_mean"),
col.close.rollingMin(windowSize = 7).alias("rolling_min"))
nbShow stock
nbText: "### Operations that sort"
tabs """
(
pl.DataFrame(
{
"x": [1, 3, None, 3, 7],
"y": ["D", "I", "S", "C", "O"],
}
).with_columns(
arg_sort=pl.col("x").arg_sort(),
shuffle=pl.col("x").shuffle(seed=7),
sort=pl.col("x").sort(nulls_last=True),
sort_by=pl.col("x").sort_by("y"),
reverse=pl.col("x").reverse(),
rank=pl.col("x").rank(),
)
)
""":
nbCode:
nbShow newDataFrame(
series("x", [some(1), some(3), none(int), some(3), some(7)]),
series("y", ["D", "I", "S", "C", "O"])
).withColumns(
col.x.argSort.alias("arg_sort"),
col.x.shuffle(seed = 7).alias("shuffle"),
col.x.sort(nullsLast = true).alias("sort"),
col.x.sortBy("y").alias("sort_by"),
col.x.reverse.alias("reverse"),
col.x.rank.alias("rank"))
nbText: """
### Other operations
`rle_id` numbers the runs of equal values:
"""
tabs """
(
pl.DataFrame({"x": [33, 33, 27, 33, 60, 60, 60, 33, 60]}).with_columns(
rle_id=pl.col("x").rle_id(),
)
)
""":
nbCode:
nbShow newDataFrame(series("x", [33, 33, 27, 33, 60, 60, 60, 33, 60])).withColumns(
col.x.rleId.alias("rle_id"))
nbText: """
## Series-wise operations that summarize to one
An aggregation in `with_columns` is broadcast to every row; in a group-by it gives one
value per group.
"""
tabs """
(
pl.DataFrame({"x": [1, 3, 3, 7]}).with_columns(
mean=pl.col("x").mean(),
)
)
""":
nbCode:
nbShow newDataFrame(series("x", [1, 3, 3, 7])).withColumns(col.x.mean.alias("mean"))
tabs """
(
pl.DataFrame({"cluster": ["a", "a", "b", "b"], "x": [1, 3, 3, 7]})
.group_by("cluster")
.agg(
mean=pl.col("x").mean(),
)
)
""":
nbCode:
nbShow newDataFrame(series("cluster", ["a", "a", "b", "b"]), series("x", [1, 3, 3, 7]))
.groupBy("cluster")
.agg(col.x.mean.alias("mean"))
nbText: """
### Operations that are quantifiers
`all` is true when every value is, `any` when at least one is:
"""
tabs """
df = pl.DataFrame(
{
"x": [True, False, False],
"y": [True, True, True],
"z": [False, False, False],
}
)
print(df)
df.select(
pl.all().all().name.suffix("_all"),
pl.all().any().name.suffix("_any"),
)
""":
nbCode:
let bools = newDataFrame:
x: [true, false, false]
y: [true, true, true]
z: [false, false, false]
echo bools
nbShow bools.select(
all().all.name.suffix("_all"),
all().any.name.suffix("_any"))
nbText: """
### Operations that compute statistics
"""
nanuq """
The book computes these on a million numbers drawn from a normal distribution with numpy.
Nanuq can't draw the same numbers, so both sides use the penguins' masses instead.
"""
tabs """
(
penguins.select(
max=pl.col("mass").max(),
mean=pl.col("mass").mean(),
quantile=pl.col("mass").quantile(quantile=0.95),
skew=pl.col("mass").skew(),
std=pl.col("mass").std(),
sum=pl.col("mass").sum(),
var=pl.col("mass").var(),
)
)
""":
nbCode:
nbShow penguins.select(
col.mass.max.alias("max"),
col.mass.mean.alias("mean"),
col.mass.quantile(0.95).alias("quantile"),
col.mass.skew.alias("skew"),
col.mass.std.alias("std"),
col.mass.sum.alias("sum"),
col.mass.var.alias("var"))
nbText: """
### Operations that count
1,729 random integers below 10,000, one of them made missing:
"""
nanuq """
The book draws the integers with numpy and sets value 403 to `None` in place. Here both
sides draw them with Polars' `sample` and a seed, and blank value 403 with a `when` that
has no `otherwise`.
"""
tabs """
df_ints = (
pl.DataFrame({"x": range(10_000)})
.sample(1_729, with_replacement=True, seed=1729)
.with_row_index()
.with_columns(x=pl.when(pl.col("index") != 403).then(pl.col("x")))
)
df_ints.slice(400, 6)
""":
nbCode:
import std/sequtils
let dfInts = newDataFrame(series("x", toSeq(0 ..< 10_000)))
.sample(1_729, withReplacement = true, seed = 1729)
.withRowIndex()
.withColumns(`when`(col.index != 403).then(col.x).alias("x"))
nbShow dfInts.slice(400, 6)
tabs """
df_ints.select(
approx_n_unique=pl.col("x").approx_n_unique(),
count=pl.col("x").count(),
len=pl.col("x").len(),
n_unique=pl.col("x").n_unique(),
null_count=pl.col("x").null_count(),
)
""":
nbCode:
nbShow dfInts.select(
col.x.approxNUnique.alias("approx_n_unique"),
col.x.count.alias("count"),
col.x.len.alias("len"),
col.x.nUnique.alias("n_unique"),
col.x.nullCount.alias("null_count"))
nbText: """
The book then times `n_unique` against `approx_n_unique` on ten million integers: the
approximation is several times faster. (Timings are left out of this book's builds.)
### Other operations
"""
tabs """
df_ints.select(
arg_min=pl.col("x").arg_min(),
first=pl.col("x").first(),
get=pl.col("x").get(403),
implode=pl.col("x").implode(),
last=pl.col("x").last(),
upper_bound=pl.col("x").upper_bound(),
)
""":
nbCode:
nbShow dfInts.select(
col.x.argMin.alias("arg_min"),
col.x.first.alias("first"),
col.x.get(403).alias("get"),
col.x.implode.alias("implode"),
col.x.last.alias("last"),
col.x.upperBound.alias("upper_bound"))
nbText: """
## Series-wise operations that summarize to one or more
### Operations related to unique values
"""
tabs """
(
pl.DataFrame({"x": ["A", "C", "D", "C"]}).select(
arg_unique=pl.col("x").arg_unique(),
unique=pl.col("x").unique(maintain_order=True),
unique_counts=pl.col("x").unique_counts(),
value_counts=pl.col("x").value_counts(sort=True),
)
)
""":
nbCode:
nbShow newDataFrame(series("x", ["A", "C", "D", "C"])).select(
col.x.argUnique.alias("arg_unique"),
col.x.unique(maintainOrder = true).alias("unique"),
col.x.uniqueCounts.alias("unique_counts"),
col.x.valueCounts(sort = true).alias("value_counts"))
nbText: "### Operations that select"
nanuq """
The book also takes a random `sample(7)`. Nanuq has it (`col.x.sample(7, seed = 42)`),
but even with a seed the order of the values depends on the Polars version, which differs
between Nanuq and Python Polars 2.1, so that column is left out.
"""
tabs """
df_ints.select(
bottom_k=pl.col("x").bottom_k(7),
head=pl.col("x").head(7),
slice=pl.col("x").slice(400, 7),
gather=pl.col("x").gather([1, 1, 2, 3, 5, 8, 13]),
gather_every=pl.col("x").gather_every(247),
top_k=pl.col("x").top_k(7),
)
""":
nbCode:
nbShow dfInts.select(
col.x.bottomK(7).alias("bottom_k"),
col.x.head(7).alias("head"),
col.x.slice(400, 7).alias("slice"),
col.x.gather([1, 1, 2, 3, 5, 8, 13]).alias("gather"),
col.x.gatherEvery(247).alias("gather_every"),
col.x.topK(7).alias("top_k"))
nbText: "### Operations that drop missing values"
tabs """
x = [None, 1.0, 2.0, 3.0, np.nan]
(
pl.DataFrame({"x": x}).select(
drop_nans=pl.col("x").drop_nans(), drop_nulls=pl.col("x").drop_nulls()
)
)
""":
nbCode:
nbShow newDataFrame(
series("x", [none(float), some(1.0), some(2.0), some(3.0), some(NaN)])
).select(
col.x.dropNans.alias("drop_nans"), col.x.dropNulls.alias("drop_nulls"))
nbText: """
### Other operations
`mode` gives the most common values (more than one when they tie):
"""
tabs """
numbers = [33, 33, 27, 33, 60, 60, 60, 33, 60]
(
pl.DataFrame({"x": numbers}).select(
arg_true=(pl.col("x") >= 60).arg_true(),
)
)
""":
nbCode:
let numbers = newDataFrame:
x: [33, 33, 27, 33, 60, 60, 60, 33, 60]
nbShow numbers.select((col.x >= 60).argTrue.alias("arg_true"))
tabs """
(
pl.DataFrame({"x": numbers}).select(
mode=pl.col("x").mode().sort(),
)
)
""":
nbCode:
nbShow numbers.select(col.x.mode.sort.alias("mode"))
nbText: "`reshape` turns the column into arrays, here three of three values:"
tabs """
(
pl.DataFrame({"x": numbers}).select(
reshape=pl.col("x").reshape((3, 3)),
)
)
""":
nbCode:
nbShow numbers.select(col.x.reshape([3, 3]).alias("reshape"))
nbText: "`rle` gives the runs of equal values, as structs of a length and a value:"
tabs """
(
pl.DataFrame({"x": numbers}).select(
rle=pl.col("x").rle(),
)
)
""":
nbCode:
nbShow numbers.select(col.x.rle.alias("rle"))
nbText: """
`search_sorted` gives the position where a value would go in a sorted column:
"""
tabs """
(
pl.DataFrame({"x": numbers}).select(
rle=pl.col("x").sort().search_sorted(42),
)
)
""":
nbCode:
nbShow numbers.select(col.x.sort.searchSorted(42).alias("rle"))
nanuq """
The chapter ends with series-wise operations that extend: `explode` turns each list into
rows.
"""
tabs """
(
pl.DataFrame(
{
"x": [["a", "b"], ["c", "d"]],
}
).select(explode=pl.col("x").explode())
)
""":
nbCode:
nbShow newDataFrame(series("x", [@["a", "b"], @["c", "d"]]))
.select(col.x.explode.alias("explode"))
bookSave()