Skip to content

Conditionals

Python's x if condition else y can't be overloaded, so zeki writes an if/else as zk.when(...).then(...).otherwise(...), as Polars does. Chain more branches with .when(...): the first branch whose conditions hold is picked. Several conditions passed to one .when(a, b) must all hold.

Over values

Over value expressions, zk.when builds a value expression for with_columns and agg, picking value by value from values of one kind:

claims = reserves.with_columns(limit=zk.float(lambda: 30_000.0))
gross_value, limit = zk.value("gross_reserves"), zk.value("limit")
claims = claims.with_columns(
    capped=zk.when(gross_value > limit).then(limit).otherwise(gross_value),
    band=zk.when(gross_value >= 40_000.0).then("large").when(gross_value > 0.0).then("attritional").otherwise("nil"),
    ratio=zk.when(gross_value != 0.0).then(limit / gross_value).otherwise(0.0),
)

A branch's value is used only where it's picked, so limit / gross_value is safe where gross_value is 0: the infinity there is never picked.

Each zk.when computes one column from named columns. It doesn't take collections: to bound a collection's values, use zk.min, zk.max or clamp.

Over dimensions

Over dimension expressions, zk.when builds a dimension expression, for group_by and filter. Here, every year from 2025 on is grouped as 2025:

year = zk.dim("underwriting_year")
zk.when(year < 2025).then(year).otherwise(2025)

See Group-by for this in use.