analog_daddy.plexpr
¶
A collection of polars expressions/idioms.
These helpers could probably be snippets in a docs page. But they have earned their place here due to their utility across different domains. Most of these are slight modifications of snippets scavenged across the internet (primarily Stackoverflow, Discord and Github) and I have attempted to credit the original sources wherever possible. You can use them as a template or building blocks for complex data processing pipelines.
all_minmax_by(expr, by, separator='__')
¶
Get values at the minimum and maximum of each by column.
If the column has multiple values equal to its minimum or maximum,
all corresponding values are returned. Polars has a min_by and
max_by expression, but they return only one value and it is not
defined which value will be chosen. Similarly, using arg_min or
arg_max will return only one value, and it is not defined which
value will be chosen.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expr
|
Expr
|
Values to return at each extremum. |
required |
by
|
Sequence[str]
|
Columns whose minimum and maximum select the values. |
required |
separator
|
str
|
The separator to use in the output column names. |
"__"
|
Returns:
| Type | Description |
|---|---|
tuple[Expr, ...]
|
|
References
- I unfortunately found this resource a bit later and it would have saved me some frustration in validating if my approach was the idiomatic.
Examples:
>>> (
... df := pl.DataFrame(
... {
... "x": ["A", "B", "C", "D", "E", "F"],
... "y": [-1, 0, 3, 4, -1, 4],
... "z": [2, 3, 10, None, 3, 10],
... }
... )
... )
shape: (6, 3)
┌─────┬─────┬──────┐
│ x ┆ y ┆ z │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════╪═════╪══════╡
│ A ┆ -1 ┆ 2 │
│ B ┆ 0 ┆ 3 │
│ C ┆ 3 ┆ 10 │
│ D ┆ 4 ┆ null │
│ E ┆ -1 ┆ 3 │
│ F ┆ 4 ┆ 10 │
└─────┴─────┴──────┘
>>> df.group_by().agg(all_minmax_by(pl.col("x"), ["y", "z"]))
shape: (1, 4)
┌─────────────┬─────────────┬─────────────┬─────────────┐
│ x_at_min__y ┆ x_at_max__y ┆ x_at_min__z ┆ x_at_max__z │
│ --- ┆ --- ┆ --- ┆ --- │
│ list[str] ┆ list[str] ┆ list[str] ┆ list[str] │
╞═════════════╪═════════════╪═════════════╪═════════════╡
│ ["A", "E"] ┆ ["D", "F"] ┆ ["A"] ┆ ["C", "F"] │
└─────────────┴─────────────┴─────────────┴─────────────┘
Source code in src/analog_daddy/plexpr.py
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 | |
item_where(expr, predicate, separator='__', prefix='item')
¶
Expression to get a single special value filtered by a predicate.
Fails when evaluated if the predicate does not filter to a single value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expr
|
Expr
|
The column to filter and get the item from. |
required |
predicate
|
Expr
|
The predicate to filter the column by. |
required |
separator
|
str
|
The separator to use in the output column name. |
"__"
|
prefix
|
str
|
The prefix to use in the output column name. |
"item"
|
Returns:
| Type | Description |
|---|---|
Expr
|
A polars expression that filters the column by the predicate and returns the single item. |
Examples:
>>> (
... df := pl.DataFrame(
... {
... "x": ["A", "B", "C", "A", "E"],
... "y": [-1, 0, 3, 4, -1],
... "z": [None, 3, 10, None, 3],
... }
... )
... )
shape: (5, 3)
┌─────┬─────┬──────┐
│ x ┆ y ┆ z │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════╪═════╪══════╡
│ A ┆ -1 ┆ null │
│ B ┆ 0 ┆ 3 │
│ C ┆ 3 ┆ 10 │
│ A ┆ 4 ┆ null │
│ E ┆ -1 ┆ 3 │
└─────┴─────┴──────┘
>>> df.select(item_where(pl.col("y", "z"), pl.col("x") == "A"))
Traceback (most recent call last):
polars.exceptions.ComputeError: ...
>>> df.select(item_where(pl.col("y", "z"), pl.col("x") == "B"))
shape: (1, 2)
┌─────────┬─────────┐
│ item__y ┆ item__z │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════════╪═════════╡
│ 0 ┆ 3 │
└─────────┴─────────┘
Source code in src/analog_daddy/plexpr.py
ksigma_bounds(expr, k=1.0, separator='__')
¶
Computes ksigma bounds, mean and standard deviation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expr
|
Expr
|
The column to compute ksigma bounds across. |
required |
k
|
float
|
The number of standard deviations to compute the bounds. |
1.0
|
separator
|
str
|
The separator to use in the output column names. |
"__"
|
Returns:
| Type | Description |
|---|---|
tuple[Expr, ...]
|
|
Examples:
>>> import numpy as np
>>> a = pl.DataFrame(
... {
... "x": np.random.default_rng(seed=12345).normal(
... loc=10, scale=2, size=1200
... ),
... "y": np.random.default_rng(seed=12345).normal(
... loc=0, scale=4, size=1200
... ),
... }
... ).with_row_index(offset=1)
>>> a.select(ksigma_bounds(pl.col("x", "y"))).select(
... pl.all().cast(pl.Decimal(scale=2))
... ).unpivot()
shape: (8, 2)
┌─────────────────┬───────────────┐
│ variable ┆ value │
│ --- ┆ --- │
│ str ┆ decimal[38,2] │
╞═════════════════╪═══════════════╡
│ mean - 1*std__x ┆ 8.05 │
│ mean - 1*std__y ┆ -3.90 │
│ mean__x ┆ 10.07 │
│ mean__y ┆ 0.14 │
│ mean + 1*std__x ┆ 12.09 │
│ mean + 1*std__y ┆ 4.18 │
│ std__x ┆ 2.02 │
│ std__y ┆ 4.04 │
└─────────────────┴───────────────┘
Source code in src/analog_daddy/plexpr.py
list_cast()
¶
Cast list columns to list[str]
Uses render to convert numeric values and casts categorical
values to string.
Returns:
| Type | Description |
|---|---|
tuple[Expr, Expr]
|
|
Examples:
>>> (
... df := pl.DataFrame(
... {"a": [[1000, 2.5e-6]], "b": [["x", "y"]]},
... schema={
... "a": pl.List(pl.Float64),
... "b": pl.List(pl.Categorical),
... },
... )
... )
shape: (1, 2)
┌─────────────────────┬────────────┐
│ a ┆ b │
│ --- ┆ --- │
│ list[f64] ┆ list[cat] │
╞═════════════════════╪════════════╡
│ [1000.0, 0.0000025] ┆ ["x", "y"] │
└─────────────────────┴────────────┘
>>> out = df.with_columns(*list_cast())
>>> out
shape: (1, 2)
┌────────────────┬────────────┐
│ a ┆ b │
│ --- ┆ --- │
│ list[str] ┆ list[str] │
╞════════════════╪════════════╡
│ ["1k", "2.5u"] ┆ ["x", "y"] │
└────────────────┴────────────┘
>>> out.schema.contains_dtype(pl.String, recursive=True)
True
>>> out.schema.contains_dtype(pl.Categorical, recursive=True)
False
Source code in src/analog_daddy/plexpr.py
list_render_unique(max_len=3)
¶
Render unique values of list[str] columns as a comma-joined string.
Lists with more than max_len unique values are truncated and
suffixed with the count of omitted values. The ordering is not
deterministic since pl.Expr.unique doesn't maintain order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_len
|
int
|
Maximum number of unique values to show before truncating. |
3
|
Returns:
| Type | Description |
|---|---|
Expr
|
Expression (over all list[str] columns) yielding a string. |
Examples:
>>> (df := pl.DataFrame({"a": [["x", "x"], ["a", "b", "c", "d", "e"]]}))
shape: (2, 1)
┌───────────────────┐
│ a │
│ --- │
│ list[str] │
╞═══════════════════╡
│ ["x", "x"] │
│ ["a", "b", … "e"] │
└───────────────────┘
>>> out = df.select(list_render_unique(max_len=3))["a"].to_list()
>>> out[0]
'x'
>>> out[1].endswith(" + 2 more")
True
Source code in src/analog_daddy/plexpr.py
minmax(expr, separator='__')
¶
Get a polars expression to compute min and max of a column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expr
|
Expr
|
The column to compute min and max across. |
required |
separator
|
str
|
The separator to use in the output column names |
"__"
|
Returns:
| Type | Description |
|---|---|
tuple[Expr, Expr]
|
A tuple of polars expressions for min and max of the input column. |
Examples:
>>> (
... df := pl.DataFrame(
... {
... "x": ["A", "B", "C", "D", "E", "F"],
... "y": [-1, 0, 3, 4, -1, 4],
... "z": [2, 3, 10, None, 3, 10],
... }
... )
... )
shape: (6, 3)
┌─────┬─────┬──────┐
│ x ┆ y ┆ z │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════╪═════╪══════╡
│ A ┆ -1 ┆ 2 │
│ B ┆ 0 ┆ 3 │
│ C ┆ 3 ┆ 10 │
│ D ┆ 4 ┆ null │
│ E ┆ -1 ┆ 3 │
│ F ┆ 4 ┆ 10 │
└─────┴─────┴──────┘
>>> df.select(minmax(pl.col("y", "z")))
shape: (1, 4)
┌────────┬────────┬────────┬────────┐
│ min__y ┆ min__z ┆ max__y ┆ max__z │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ i64 │
╞════════╪════════╪════════╪════════╡
│ -1 ┆ 2 ┆ 4 ┆ 10 │
└────────┴────────┴────────┴────────┘
Source code in src/analog_daddy/plexpr.py
spec(col, spec, _near_tolerance=0)
¶
Apply a specification string to a column as a polars expression.
The spec string allows an ergonomic grammer for specifying
constraints.
- Supports SI-prefixes using quantiphy (e.g. 10m = 0.01, 0.01k = 10)
- Supports simple column references col("name"), which resolves to pl.col("name").
TODO: Support ternary of pass/fail and near using _near_tolerance in future.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col
|
Expr
|
The column expression to test against the spec. |
required |
spec
|
str
|
The spec string to parse. |
required |
_near_tolerance
|
float
|
The tolerance for near matches, currently unused. |
0
|
Returns:
| Type | Description |
|---|---|
Expr
|
A boolean expression that evaluates to True if the value in
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the spec string is invalid or cannot be parsed. |
Examples:
>>> df = pl.from_repr(r'''shape: (2, 3)
... ┌──────┬──────┬─────┐
... │ x ┆ foo ┆ bar │
... │ --- ┆ --- ┆ --- │
... │ f64 ┆ f64 ┆ f64 │
... ╞══════╪══════╪═════╡
... │ 9.0 ┆ 10.0 ┆ 5.0 │
... │ 11.0 ┆ 10.0 ┆ 5.0 │
... └──────┴──────┴─────┘
... ''')
>>> lit_specs = [
... "> 10m",
... "< 0.01k",
... "range 8000m 10500m",
... "tolerance 10 20",
... ]
>>> df.select(*(spec(pl.col("x"), s).alias(s) for s in lit_specs))
shape: (2, 4)
┌───────┬─────────┬────────────────────┬─────────────────┐
│ > 10m ┆ < 0.01k ┆ range 8000m 10500m ┆ tolerance 10 20 │
│ --- ┆ --- ┆ --- ┆ --- │
│ bool ┆ bool ┆ bool ┆ bool │
╞═══════╪═════════╪════════════════════╪═════════════════╡
│ true ┆ true ┆ true ┆ true │
│ true ┆ false ┆ false ┆ true │
└───────┴─────────┴────────────────────┴─────────────────┘
>>> calc_specs = {
... "range": 'range col("bar") col("foo")',
... "gt": '> col("foo")',
... "tol": 'tolerance col("foo") col("bar")',
... }
>>> print(
... df.select(
... *(
... spec(pl.col("x"), s).alias(name)
... for name, s in calc_specs.items()
... )
... ).write_csv()
... )
range,gt,tol
true,false,false
false,true,false
Source code in src/analog_daddy/plexpr.py
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 | |