Created
August 5, 2025 15:17
-
-
Save TJMac93/ecff5c499f68808e360f361f13e1ae99 to your computer and use it in GitHub Desktop.
How to use generic polars expressions and register new ones.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import polars as pl | |
df1 = pl.DataFrame({"A":[1,2 ,3 ,4 ,5 ,6], "B":[1,5,9,1,2,3]}) | |
df2 = pl.DataFrame({"A":[5,10,15,20,25,30], "B":[1,5,9,1,2,3]}) | |
dbl_expr = pl.col("A") * 2 | |
sq_expr = pl.col("A") ** 2 | |
df1.with_columns(dbl_A = dbl_expr, | |
sq_A = sq_expr) | |
# Register your own custom functrionality in a reusable name | |
@pl.api.register_expr_namespace("double_and_compute_n") # This is the name of the expression group that is run on a selection | |
class DoubleCompN: | |
def __init__(self, expr: pl.Expr) -> None: | |
self._expr = expr # This represents the expression where it is called e.g. `pl.col("A")` in `pl.col("A").double_and_compute_n.add(5)` | |
def add(self, n: int)-> pl.Expr: | |
return ((self._expr * 2) + n) | |
def subtract(self, n: int)-> pl.Expr: | |
return ((self._expr * 2) - n) | |
df1.with_columns( | |
pl.col("A"), | |
(pl.col("A") * 2).alias('2n'), | |
(pl.col("A").double_and_compute_n.add(3)).alias("da3"), | |
(pl.col("A").double_and_compute_n.subtract(10).alias("ds10")) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
df1.with_columns(dbl_A = dbl_expr, sq_A = sq_expr)