This post was written before the code it shows. We drafted it while Nanuq 0.2 was still being designed, used it to decide the API, and checked every output against the same steps run in Python Polars. Now 0.2 is built and the page runs for real: each output below comes from Nanuq, and the page build compares it with the Python one.
Every spring, the rangers of Svalbard radio in the polar bears they see, and someone at base has to turn their notes into a report. This post follows one season of those notes through everything new in Nanuq 0.2: data types and casts, joins and concatenation, frame verbs, CSV reading options, conditional expressions, window functions and column selectors. A spring's worth of field logs needs every one of them.
Why anyone counts polar bearsβ contents
Svalbard's polar bears are counted for real, and the real numbers are small. An aerial survey in August 2015 estimated about 264 bears on the islands themselves, and about 973 including the pack ice to the north (Aars et al. 2017). Every spring since the 1990s, from March to May, the Norwegian Polar Institute has captured and marked bears, recording sex, weight, length and body condition, and it counts maternity dens on islands such as Hopen and KongsΓΈya (MOSJ).
Our census is invented, but it is shaped like that work: five stations, four weeks of spring, one row per station per week (the week is a plain number: date types come in a later release). Each row has the bears seen, the cubs among them, the weight of one bear weighed that week, whether it wore a collar, and the seals it was seen eating.
The first weekβ contents
Week one came in from four stations. Ingrid saw "lots" of bears and couldn't weigh any
of them, so she wrote ?.
let week1 = readCsv("data/logs/week_01.csv")
echo week1
shape: (4, 9) ββββββββ¬βββββββββββββββ¬βββββββββ¬ββββββββ¬βββββββ¬ββββββββββββ¬βββββββββββ¬βββββββββ¬ββββββββββ β week β station β ranger β bears β cubs β weight_kg β collared β ringed β bearded β β --- β --- β --- β --- β --- β --- β --- β --- β --- β β i64 β str β str β str β i64 β str β i64 β i64 β i64 β ββββββββͺβββββββββββββββͺβββββββββͺββββββββͺβββββββͺββββββββββββͺβββββββββββͺβββββββββͺββββββββββ‘ β 1 β Longyearbyen β Ingrid β lots β 2 β ? β 0 β 3 β 0 β β 1 β Ny-Alesund β Ola β 1 β 0 β 389.0 β 1 β 2 β 0 β β 1 β Barentsburg β Sasha β 0 β 0 β null β 0 β 0 β 0 β β 1 β Hornsund β Kari β 3 β 1 β 515.0 β 1 β 5 β 1 β ββββββββ΄βββββββββββββββ΄βββββββββ΄ββββββββ΄βββββββ΄ββββββββββββ΄βββββββββββ΄βββββββββ΄ββββββββββ
bears and weight_kg are strings: Polars doesn't guess that "lots" is a number or
that ? means "don't know". Barentsburg left the weight empty, which already reads as
null.
Reading the whole seasonβ contents
The logs are one file per week. Polars can read all of them lazily with one glob, and
0.2 adds the reading options from Polars' CSV reader: here, ? is a null value, and
two columns get their type up front with schemaOverrides, which takes DataType
values just like cast. bears stays text for now; we'll come back to "lots".
try:
discard scanCsv("data/logs/*.csv", nullValues = ["?"],
schemaOverrides = {"bears": String, "weight_kg": Float64}).collect
except PolarsError as e:
echo e.msg.splitLines[0]
schema lengths differ
It fails. In week two a fifth station joined: Hopen, a small island in the
southeast where bears den every winter. Its ranger, Magnus, also measures the sea ice,
so from week two the logs have an extra ice_cm column, and a glob needs every file
to have the same columns.
So read each week separately and stack them with a diagonal concat, which matches columns by name and fills the missing ones with nulls.
var weeks: seq[LazyFrame]
for week in 1..4:
weeks.add scanCsv("data/logs/week_0" & $week & ".csv", nullValues = ["?"],
schemaOverrides = {"bears": String, "weight_kg": Float64})
let season = concat(weeks, how = Diagonal)
for name, t in season.collectSchema:
echo name.alignLeft(15), t
week Int64 station String ranger String bears String cubs Int64 weight_kg Float64 collared Int64 ringed Int64 bearded Int64 ice_cm Int64
Nothing has been read yet: collectSchema works out the result's types from the plan
alone.
"Lots" is not a numberβ contents
A cast is strict by default, as in Polars: if a single value can't be converted, the query fails, and the error names the culprit. The target can be a plain Nim type.
try:
discard season.select(col("bears").cast(int)).collect
except PolarsError as e:
echo e.msg.splitLines[0]
conversion from `str` to `i64` failed in column 'bears' for 1 out of 4 values: ["lots"]
A non-strict cast turns what it can't read into nulls. That's the honest reading of
"lots": there were bears, we don't know how many. Cubs fit in a uint8, and the
1/0 collar column becomes a boolean.
let log = season.cast({"bears": Int64, "cubs": UInt8, "collared": Boolean},
strict = false).collect
echo log.dtypes
echo "bear counts we couldn't read: ", log.nullCount("bears")
@[Int64, String, String, Int64, UInt8, Float64, Boolean, Int64, Int64, Int64] bear counts we couldn't read: 2
Two: Ingrid's "lots" and Kari's "many".
Ola radios everything twiceβ contents
Ola, at Ny-Γ
lesund, has a habit of radioing his report twice when the line is bad. Two
identical rows are one report, so unique drops the copy. maintainOrder keeps the
rows in the order they came in, and a row index gives each report a number.
let tidy = log.unique(maintainOrder = true).withRowIndex("report", offset = 1)
echo "reports: ", log.height, " radioed, ", tidy.height, " after unique"
echo tidy.select(col("report", "week", "station", "ranger", "bears")).tail(3)
reports: 20 radioed, 19 after unique shape: (3, 5) ββββββββββ¬βββββββ¬ββββββββββββββ¬βββββββββ¬ββββββββ β report β week β station β ranger β bears β β --- β --- β --- β --- β --- β β u32 β i64 β str β str β i64 β ββββββββββͺβββββββͺββββββββββββββͺβββββββββͺββββββββ‘ β 17 β 4 β Barentsburg β Sasha β 3 β β 18 β 4 β Hornsund β Kari β 2 β β 19 β 4 β Hopen β Magnus β 6 β ββββββββββ΄βββββββ΄ββββββββββββββ΄βββββββββ΄ββββββββ
col with several names selects several columns at once, new in 0.2.
Who was on duty?β contents
Twice a ranger forgot to write their name. Each station has one ranger, so the name
from the station's previous report is the right one. The obvious fix, a forward fill,
takes the name from the row above, and the row above belongs to another station.
Adding .over("station") makes the fill run within each station, a window in
Polars' terms.
echo tidy
.select(col("report", "station", "ranger"),
col("ranger").fillNull(Forward).alias("naive"),
col("ranger").forwardFill.over("station").alias("per_station"))
.filter(col("ranger").isNull)
shape: (2, 5) ββββββββββ¬ββββββββββββββ¬βββββββββ¬βββββββββ¬ββββββββββββββ β report β station β ranger β naive β per_station β β --- β --- β --- β --- β --- β β u32 β str β str β str β str β ββββββββββͺββββββββββββββͺβββββββββͺβββββββββͺββββββββββββββ‘ β 12 β Barentsburg β null β Ola β Sasha β β 16 β Ny-Alesund β null β Ingrid β Ola β ββββββββββ΄ββββββββββββββ΄βββββββββ΄βββββββββ΄ββββββββββββββ
The naive fill would have put Ola in Barentsburg and Ingrid in Ny-Γ lesund.
Sanity checksβ contents
Adult male polar bears weigh roughly 300 to 600 kg and can reach 800; females are about
half that (Norwegian Polar Institute). Anything outside
150 to 800 kg is a typo, so we drop it to null. That's a conditional expression, and
in Nanuq you write it with choose and an ordinary Nim if. Without an else, the
value is null, as in Polars.
Two stations, Longyearbyen and Barentsburg, are towns, where a bear is a safety
matter; isIn flags them.
let filled = tidy.withColumns(col("ranger").forwardFill.over("station"))
let checked = filled.withColumns(
choose(if col("weight_kg").isBetween(150, 800): col("weight_kg")).alias("weight_kg"),
col("station").isIn(["Longyearbyen", "Barentsburg"]).alias("near_people"))
echo checked.filter(col("station") == "Ny-Alesund")
.select(col("report", "station", "weight_kg", "near_people"))
shape: (4, 4) ββββββββββ¬βββββββββββββ¬ββββββββββββ¬ββββββββββββββ β report β station β weight_kg β near_people β β --- β --- β --- β --- β β u32 β str β f64 β bool β ββββββββββͺβββββββββββββͺββββββββββββͺββββββββββββββ‘ β 2 β Ny-Alesund β 389.0 β false β β 6 β Ny-Alesund β 451.2 β false β β 11 β Ny-Alesund β null β false β β 16 β Ny-Alesund β 295.0 β false β ββββββββββ΄βββββββββββββ΄ββββββββββββ΄ββββββββββββββ
Report 11 said 1420 kg. Ola meant 142.0, but we can't know that, so it's null now.
Where are the stations?β contents
Base keeps a small table of station coordinates. Joining it adds latitude and longitude
to every report. Each report should match at most one station, and validate checks
exactly that:
let stations = readCsv("data/stations.csv")
try:
discard checked.join(stations, on = ["station"], how = Left, validate = ManyToOne)
except PolarsError as e:
echo e.msg.splitLines[0]
join keys did not fulfill m:1 validation
Someone typed Hornsund in twice. And is any station missing from the table? An anti join keeps the reports that have no match:
echo checked.join(stations, on = ["station"], how = Anti).select(col("station")).unique
shape: (1, 1) βββββββββββ β station β β --- β β str β βββββββββββ‘ β Hopen β βββββββββββ
Nobody added Hopen. Fine for now: a left join keeps Hopen's reports, with null coordinates.
Slim, solid or chonkβ contents
Time to name the bears' sizes. choose takes a whole if/elif/else chain, and
turns it into Polars' when/then/otherwise, so the order matters: the first true
branch wins. The null check comes first, because a comparison with null is null, which
isn't true, so without it every unweighed bear would fall through to "chonk".
Polar bears live mostly on seals. Ringed seals are the main prey, and one big bearded seal is worth about ten ringed ones, so the log gets a column of ringed-seal equivalents too.
let located = checked.join(stations.unique(maintainOrder = true), on = ["station"],
how = Left, validate = ManyToOne,
maintainOrder = MaintainOrderJoin.Left)
let size = choose:
if col("weight_kg").isNull: "unweighed"
elif col("weight_kg") < 200: "slim"
elif col("weight_kg") < 450: "solid"
else: "chonk"
let sized = located.withColumns(size.alias("size"),
(col("ringed") + 10 * col("bearded")).alias("seal_eq"))
echo sized.select(col("station", "weight_kg", "size", "ringed", "bearded", "seal_eq")).head(8)
shape: (8, 6) ββββββββββββββββ¬ββββββββββββ¬ββββββββββββ¬βββββββββ¬ββββββββββ¬ββββββββββ β station β weight_kg β size β ringed β bearded β seal_eq β β --- β --- β --- β --- β --- β --- β β str β f64 β str β i64 β i64 β i64 β ββββββββββββββββͺββββββββββββͺββββββββββββͺβββββββββͺββββββββββͺββββββββββ‘ β Longyearbyen β null β unweighed β 3 β 0 β 3 β β Ny-Alesund β 389.0 β solid β 2 β 0 β 2 β β Barentsburg β null β unweighed β 0 β 0 β 0 β β Hornsund β 515.0 β chonk β 5 β 1 β 15 β β Longyearbyen β 412.5 β solid β 3 β 0 β 3 β β Ny-Alesund β 451.2 β chonk β 4 β 1 β 14 β β Barentsburg β 402.8 β solid β 4 β 0 β 4 β β Hornsund β 622.0 β chonk β 7 β 2 β 27 β ββββββββββββββββ΄ββββββββββββ΄ββββββββββββ΄βββββββββ΄ββββββββββ΄ββββββββββ
A bare string in choose is a value. (In Python Polars, then("slim") would look for
a column named "slim", a classic surprise; Nanuq takes columns only through col.)
Each bear against its stationβ contents
Hornsund keeps weighing heavy bears. How heavy compared with Hornsund's usual? A mean
over the station gives every row its station's average, without collapsing the rows
the way groupBy would.
echo sized.filter(col("station") == "Hornsund").select(
col("week"), col("weight_kg"),
(col("weight_kg") - col("weight_kg").mean.over("station")).round(1).alias("vs_station"))
shape: (4, 3) ββββββββ¬ββββββββββββ¬βββββββββββββ β week β weight_kg β vs_station β β --- β --- β --- β β i64 β f64 β f64 β ββββββββͺββββββββββββͺβββββββββββββ‘ β 1 β 515.0 β -76.8 β β 2 β 622.0 β 30.2 β β 3 β 588.3 β -3.5 β β 4 β 641.9 β 50.1 β ββββββββ΄ββββββββββββ΄βββββββββββββ
Every number, per stationβ contents
For the station summary we want the mean of every numeric column, apart from a few
that make no sense to average. Column selectors pick columns by type, and Nanuq uses
Nim's own type classes for it: col(SomeNumber) is every numeric column,
col(SomeFloat) every float column, col(int, float) exactly those types.
Averaging many columns at once would give them all the same name, so name.suffix
renames each one.
echo sized.groupBy(col("station"))
.agg(col(SomeNumber).exclude("report", "week", "cubs", "ringed", "bearded", "lat", "lon")
.mean.round(1).name.suffix("_mean"))
.sort("station")
shape: (5, 5) ββββββββββββββββ¬βββββββββββββ¬βββββββββββββββββ¬ββββββββββββββ¬βββββββββββββββ β station β bears_mean β weight_kg_mean β ice_cm_mean β seal_eq_mean β β --- β --- β --- β --- β --- β β str β f64 β f64 β f64 β f64 β ββββββββββββββββͺβββββββββββββͺβββββββββββββββββͺββββββββββββββͺβββββββββββββββ‘ β Barentsburg β 1.5 β 258.9 β null β 4.8 β β Hopen β 5.0 β 233.7 β 92.7 β 15.0 β β Hornsund β 2.3 β 591.8 β null β 19.0 β β Longyearbyen β 1.0 β 390.0 β null β 1.8 β β Ny-Alesund β 1.8 β 378.4 β null β 5.2 β ββββββββββββββββ΄βββββββββββββ΄βββββββββββββββββ΄ββββββββββββββ΄βββββββββββββββ
Hopen sees the most bears but weighs the lightest. That fits: Hopen is a denning island, and the bears Magnus weighs are mostly mothers with cubs, who are about half a male's size. A mother usually has two cubs, and four or five in a week is a busy spring. Hornsund, meanwhile, is where the big males are.
The season's weights in three numbers:
echo sized.select(col("weight_kg").median.alias("median"),
col("weight_kg").quantile(0.9).alias("p90"),
col("weight_kg").std.round(1).alias("std"))
shape: (1, 3) ββββββββββ¬ββββββββ¬ββββββββ β median β p90 β std β β --- β --- β --- β β f64 β f64 β f64 β ββββββββββͺββββββββͺββββββββ‘ β 389.0 β 622.0 β 156.3 β ββββββββββ΄ββββββββ΄ββββββββ
The report for the Governorβ contents
Polar bears have been protected since the 1973 international agreement on their
conservation, signed in Oslo, and Svalbard's bear reports go to the Governor's office.
The Governor likes the heaviest bears first and the unknowns at the end: a sort by two
keys, with nullsLast.
let report = sized
.sort(["weight_kg", "week"], descending = [true, false], nullsLast = [true])
.select(col("week", "station", "ranger", "bears", "weight_kg", "size", "seal_eq"))
echo report
shape: (19, 7) ββββββββ¬βββββββββββββββ¬βββββββββ¬ββββββββ¬ββββββββββββ¬ββββββββββββ¬ββββββββββ β week β station β ranger β bears β weight_kg β size β seal_eq β β --- β --- β --- β --- β --- β --- β --- β β i64 β str β str β i64 β f64 β str β i64 β ββββββββͺβββββββββββββββͺβββββββββͺββββββββͺββββββββββββͺββββββββββββͺββββββββββ‘ β 4 β Hornsund β Kari β 2 β 641.9 β chonk β 18 β β 2 β Hornsund β Kari β null β 622.0 β chonk β 27 β β 3 β Hornsund β Kari β 2 β 588.3 β chonk β 16 β β 1 β Hornsund β Kari β 3 β 515.0 β chonk β 15 β β 2 β Ny-Alesund β Ola β 3 β 451.2 β chonk β 14 β β 2 β Longyearbyen β Ingrid β 2 β 412.5 β solid β 3 β β 2 β Barentsburg β Sasha β 2 β 402.8 β solid β 4 β β 1 β Ny-Alesund β Ola β 1 β 389.0 β solid β 2 β β 3 β Longyearbyen β Ingrid β 1 β 367.4 β solid β 1 β β 4 β Ny-Alesund β Ola β 1 β 295.0 β solid β 2 β β 3 β Hopen β Magnus β 5 β 241.7 β solid β 15 β β 2 β Hopen β Magnus β 4 β 233.0 β solid β 6 β β 4 β Hopen β Magnus β 6 β 226.3 β solid β 24 β β 3 β Barentsburg β Sasha β 1 β 198.6 β slim β 2 β β 4 β Barentsburg β Sasha β 3 β 175.2 β slim β 13 β β 1 β Longyearbyen β Ingrid β null β null β unweighed β 3 β β 1 β Barentsburg β Sasha β 0 β null β unweighed β 0 β β 3 β Ny-Alesund β Ola β 2 β null β unweighed β 3 β β 4 β Longyearbyen β Ingrid β 0 β null β unweighed β 0 β ββββββββ΄βββββββββββββββ΄βββββββββ΄ββββββββ΄ββββββββββββ΄ββββββββββββ΄ββββββββββ
The Governor's auditor checks three reports at random by radio. A seed makes the pick repeatable, which matters on a page that is rebuilt on every change:
echo report.sample(3, seed = 42)
shape: (3, 7) ββββββββ¬βββββββββββββββ¬βββββββββ¬ββββββββ¬ββββββββββββ¬ββββββββββββ¬ββββββββββ β week β station β ranger β bears β weight_kg β size β seal_eq β β --- β --- β --- β --- β --- β --- β --- β β i64 β str β str β i64 β f64 β str β i64 β ββββββββͺβββββββββββββββͺβββββββββͺββββββββͺββββββββββββͺββββββββββββͺββββββββββ‘ β 3 β Barentsburg β Sasha β 1 β 198.6 β slim β 2 β β 2 β Longyearbyen β Ingrid β 2 β 412.5 β solid β 3 β β 4 β Longyearbyen β Ingrid β 0 β null β unweighed β 0 β ββββββββ΄βββββββββββββββ΄βββββββββ΄ββββββββ΄ββββββββββββ΄ββββββββββββ΄ββββββββββ
(Python Polars, with the same seed, picks the same three reports in another order: a seed makes a sample repeatable within one version of Polars, not across versions.)
The office's spreadsheet is Norwegian, so the headers go Norwegian, the separator is a
semicolon, and decimals use a comma: all options of writeCsv in 0.2.
let norsk = report.rename({"week": "uke", "station": "stasjon", "bears": "isbjorner",
"weight_kg": "vekt_kg", "size": "storrelse",
"seal_eq": "sel_ekv"})
norsk.writeCsv("governor.csv", separator = ';', decimalComma = true)
echo readFile("governor.csv").splitLines[0..3].join("\n")
uke;stasjon;ranger;isbjorner;vekt_kg;storrelse;sel_ekv 4;Hornsund;Kari;2;641,9;chonk;18 2;Hornsund;Kari;;622,0;chonk;27 3;Hornsund;Kari;2;588,3;chonk;16
Late ice, light cubsβ contents
One last table. Hopen's station has also logged its maternity dens for the past eleven years: how many dens were found, the mean weight of the cubs when they first came out in spring, and the day of the year the sea ice reached the island the autumn before. Pregnant females need that ice to reach the island and den there.
let dens = readCsv("data/dens.csv")
let iceArrived = choose:
if col("ice_day") < 335: "before December"
else: "December or later"
echo dens.withColumns(iceArrived.alias("ice_arrived"))
.groupBy(col("ice_arrived"))
.agg(col("year").len.alias("years"),
col("dens").mean.round(1).alias("dens"),
col("cub_kg").mean.round(2).alias("cub_kg"))
.sort("ice_arrived", descending = true)
shape: (2, 4) βββββββββββββββββββββ¬ββββββββ¬βββββββ¬βββββββββ β ice_arrived β years β dens β cub_kg β β --- β --- β --- β --- β β str β u32 β f64 β f64 β βββββββββββββββββββββͺββββββββͺβββββββͺβββββββββ‘ β before December β 5 β 26.6 β 11.34 β β December or later β 6 β 14.2 β 9.75 β βββββββββββββββββββββ΄ββββββββ΄βββββββ΄βββββββββ
In years when the ice came late, there were fewer dens and the cubs were lighter.
These numbers are made up, but the pattern is real: on Hopen, later autumn sea ice has gone with lighter mothers and cubs at den emergence (Derocher et al. 2011). The full picture is less simple: Svalbard's bears have so far kept, and even improved, their body condition while the ice declined, which researchers expect to change as the ice keeps retreating.
What this post used from Nanuq 0.2β contents
Everything on this page, in the order it appeared:
- reading options for CSV files (
nullValues,schemaOverrides, ...) and lazyscanCsv, and writing options (separator,decimalComma, ...); concat(vertical, horizontal, diagonal) andjoin(inner, left, right, full, semi, anti, cross) withvalidate;- data types and casts, strict or not;
- frame verbs:
unique,withRowIndex,tail,sample,rename,drop,slice,reverse, and sorting by several keys withnullsLast; - conditional expressions with
choose, andisBetween,isIn,round; - null filling strategies (
fillNull(Forward),forwardFill); - window expressions with
over, andmedian,quantile,std; - column selectors: several names, Nim type classes,
exclude, andname.suffix.
The Python twin of this post, which recorded the outputs it is checked against, is blog/census/expected.py. How these APIs were chosen is in Designing Nanuq 0.2.
Source filesβ contents
Every source file this page mentions, folded: tap one to read it. A file's name in the text leads here.
docs/blog/census/expected.py 185 lines
"""Expected outputs for docs/blog/bear_census.nim, computed with py-polars.
Each function here repeats one Nim code block of the post with py-polars and
writes what that block prints to expected/<scene>.txt. The post was drafted
against these outputs before Nanuq 0.2 existed; now that it runs, rendering it
fails when a Nanuq output differs. Run from this folder: python3 -I expected.py
"""
import os, io, contextlib
import polars as pl
import polars.selectors as cs
pl.Config(tbl_rows=25, tbl_cols=12, tbl_width_chars=120, tbl_hide_dataframe_shape=False)
os.chdir(os.path.dirname(os.path.abspath(__file__)))
os.makedirs("expected", exist_ok=True)
def short(t): # Nanuq's `$` on a DataType prints Nanuq code: Int64, String, ...
simple = str(t)
if "(" in simple:
raise ValueError(f"no Nanuq name for {simple} in this scene")
return simple
def first_line(e):
return str(e).splitlines()[0]
def scene(name):
def deco(f):
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
f()
with open(f"expected/{name}.txt", "w") as fh:
fh.write(buf.getvalue().rstrip("\n") + "\n")
return f
return deco
WEEKS = [f"data/logs/{w}" for w in sorted(os.listdir("data/logs"))]
NULLS = ["?"]
OVERRIDES = {"bears": pl.String, "weight_kg": pl.Float64}
@scene("s01_first_week")
def _():
week1 = pl.read_csv(WEEKS[0])
print(week1)
@scene("s02_scan_glob")
def _():
try:
pl.scan_csv("data/logs/*.csv", null_values=NULLS, schema_overrides=OVERRIDES).collect()
except Exception as e:
print(first_line(e))
season = pl.concat([pl.scan_csv(w, null_values=NULLS, schema_overrides=OVERRIDES) for w in WEEKS],
how="diagonal")
@scene("s03_scan_concat")
def _():
for name, t in season.collect_schema().items():
print(f"{name:<15}{short(t)}")
@scene("s04_strict")
def _():
try:
season.select(pl.col("bears").cast(pl.Int64)).collect()
except Exception as e:
print(first_line(e))
log = season.cast({"bears": pl.Int64, "cubs": pl.UInt8, "collared": pl.Boolean},
strict=False).collect()
@scene("s05_cast")
def _():
print("@[" + ", ".join(short(t) for t in log.dtypes) + "]")
print("bear counts we couldn't read:", log["bears"].null_count())
tidy = log.unique(maintain_order=True).with_row_index("report", offset=1)
@scene("s06_tidy")
def _():
print(f"reports: {log.height} radioed, {tidy.height} after unique")
print(tidy.select("report", "week", "station", "ranger", "bears").tail(3))
@scene("s07_fill")
def _():
print(tidy.select("report", "station", "ranger",
pl.col("ranger").fill_null(strategy="forward").alias("naive"),
pl.col("ranger").forward_fill().over("station").alias("per_station"))
.filter(pl.col("ranger").is_null()))
filled = tidy.with_columns(pl.col("ranger").forward_fill().over("station"))
checked = filled.with_columns(
pl.when(pl.col("weight_kg").is_between(150, 800)).then(pl.col("weight_kg")).alias("weight_kg"),
pl.col("station").is_in(["Longyearbyen", "Barentsburg"]).alias("near_people"),
)
@scene("s08_sanity")
def _():
print(checked.filter(pl.col("station") == "Ny-Alesund")
.select("report", "station", "weight_kg", "near_people"))
stations = pl.read_csv("data/stations.csv")
@scene("s09_join_validate")
def _():
try:
checked.join(stations, on="station", how="left", validate="m:1")
except Exception as e:
print(first_line(e))
@scene("s10_join_anti")
def _():
print(checked.join(stations, on="station", how="anti").select("station").unique())
located = checked.join(stations.unique(maintain_order=True), on="station", how="left",
validate="m:1", maintain_order="left")
sized = located.with_columns(
pl.when(pl.col("weight_kg").is_null()).then(pl.lit("unweighed"))
.when(pl.col("weight_kg") < 200).then(pl.lit("slim"))
.when(pl.col("weight_kg") < 450).then(pl.lit("solid"))
.otherwise(pl.lit("chonk")).alias("size"),
(pl.col("ringed") + 10 * pl.col("bearded")).alias("seal_eq"),
)
@scene("s11_size")
def _():
print(sized.select("station", "weight_kg", "size", "ringed", "bearded", "seal_eq")
.head(8))
@scene("s12_over")
def _():
print(sized.filter(pl.col("station") == "Hornsund").select(
"week", "weight_kg",
(pl.col("weight_kg") - pl.col("weight_kg").mean().over("station")).round(1)
.alias("vs_station")))
@scene("s13_selectors")
def _():
print(sized.group_by("station").agg(
cs.numeric().exclude("report", "week", "cubs", "ringed", "bearded", "lat", "lon")
.mean().round(1).name.suffix("_mean"))
.sort("station"))
@scene("s14_quantile")
def _():
print(sized.select(
pl.col("weight_kg").median().alias("median"),
pl.col("weight_kg").quantile(0.9).alias("p90"),
pl.col("weight_kg").std().round(1).alias("std")))
report = (sized.sort(["weight_kg", "week"], descending=[True, False], nulls_last=True)
.select("week", "station", "ranger", "bears", "weight_kg", "size", "seal_eq"))
@scene("s15_report")
def _():
print(report)
@scene("s16_spot")
def _():
print(report.sample(3, seed=42))
@scene("s17_norsk")
def _():
norsk = report.rename({"week": "uke", "station": "stasjon", "bears": "isbjorner",
"weight_kg": "vekt_kg", "size": "storrelse", "seal_eq": "sel_ekv"})
norsk.write_csv("governor.csv", separator=";", decimal_comma=True)
with open("governor.csv") as fh:
print("".join(fh.readlines()[:4]).rstrip())
os.remove("governor.csv")
dens = pl.read_csv("data/dens.csv")
@scene("s18_dens")
def _():
print(dens.with_columns(
pl.when(pl.col("ice_day") < 335).then(pl.lit("before December"))
.otherwise(pl.lit("December or later")).alias("ice_arrived"))
.group_by("ice_arrived").agg(
pl.col("year").len().alias("years"),
pl.col("dens").mean().round(1).alias("dens"),
pl.col("cub_kg").mean().round(2).alias("cub_kg"))
.sort("ice_arrived", descending=True))
for f in sorted(os.listdir("expected")):
print("===", f)
print(open(f"expected/{f}").read())docs/blog/census/expected.py