Skip to content

Instantly share code, notes, and snippets.

@NikolayXHD
Last active August 22, 2025 16:57
Show Gist options
  • Save NikolayXHD/4be122f9559b0779f70b890e62d1a3d0 to your computer and use it in GitHub Desktop.
Save NikolayXHD/4be122f9559b0779f70b890e62d1a3d0 to your computer and use it in GitHub Desktop.
Visual number comparison for polars dataframe, similar to calc / excel conditional cell formatting
"""
┌──────────┬──────────┬──────────┬─────────────┬─────────────┬───────┬───────┬───────────┬────────┬───────┬───────┬───────────┬────────┬───────────┐
│ new_data ┆ old_data ┆ balanced ┆ auc_w_no ┆ auc_w_yes ┆ w_no ┆ w_no ┆ w_no ┆ w_no ┆ w_yes ┆ w_yes ┆ w_yes ┆ w_yes ┆ threshold │
│ ┆ ┆ ┆ ┆ ┆ auc ┆ f1 ┆ precision ┆ recall ┆ auc ┆ f1 ┆ precision ┆ recall ┆ │
╞══════════╪══════════╪══════════╪═════════════╪═════════════╪═══════╪═══════╪═══════════╪════════╪═══════╪═══════╪═══════════╪════════╪═══════════╡
│ false ┆ true ┆ false ┆ ┆ ┆ 0.827 ┆ 0.214 ┆ 0.597 ┆ 0.131 ┆ 0.704 ┆ 0.015 ┆ 0.597 ┆ 0.007 ┆ 0.896 │
│ true ┆ false ┆ false ┆ ▒▒▒▒▒▒▒▒▒▒ ┆ ▒▒▒▒▒▒▒▒▒▒ ┆ 0.886 ┆ 0.574 ┆ 0.603 ┆ 0.548 ┆ 0.823 ┆ 0.174 ┆ 0.609 ┆ 0.101 ┆ 0.440 │
│ true ┆ false ┆ true ┆ ▒▒▒▒▒▒▒▒▌ ┆ ▒▒▒▒▒▒▒▒▉ ┆ 0.878 ┆ 0.557 ┆ 0.600 ┆ 0.519 ┆ 0.811 ┆ 0.121 ┆ 0.655 ┆ 0.067 ┆ 0.997 │
│ true ┆ true ┆ false ┆ ▓▓▓▓▓▓▓▓▓▉ ┆ ▓▓▓▓▓▓▓▓▎ ┆ 0.886 ┆ 0.570 ┆ 0.599 ┆ 0.544 ┆ 0.804 ┆ 0.210 ┆ 0.606 ┆ 0.127 ┆ 0.595 │
│ true ┆ true ┆ true ┆ ▓▓▓▓▓▓▓▓▓▎ ┆ ▓▓▓▓▓▓▓▓▓▍ ┆ 0.882 ┆ 0.570 ┆ 0.602 ┆ 0.541 ┆ 0.817 ┆ 0.121 ┆ 0.609 ┆ 0.067 ┆ 0.962 │
└──────────┴──────────┴──────────┴─────────────┴─────────────┴───────┴───────┴───────────┴────────┴───────┴───────┴───────────┴────────┴───────────┘
"""
import polars as pl
BAR_CHARACTERS = list(' ▏▎▍▌▋▊▉█')
GRADIENT_CHARACTERS = list('░▒▓█')
def visual_bar_expr(
src: pl.Expr,
bar_size: int = 100,
negate: bool = False,
grp_src: pl.Expr | None = None,
) -> pl.Expr:
normalized_expr = (src - src.min()) / (src.max() - src.min())
if negate:
normalized_expr = 1 - normalized_expr
normalized_expr = normalized_expr * bar_size
if grp_src is None:
full_char_expr = pl.lit(BAR_CHARACTERS).list.get(8)
else:
full_char_expr = pl.lit(GRADIENT_CHARACTERS).list.get(
grp_src.rle_id() % len(GRADIENT_CHARACTERS)
)
return (
pl.concat_list(
full_char_expr.repeat_by(0 + normalized_expr // 8),
pl.lit(BAR_CHARACTERS).list.get(normalized_expr % 8),
)
.list.join('')
.alias('visual')
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment