Applying a polars Expression to a Polars series

Here’s a toy example to illustrate an idea:

import polars as pl

series = pl.Series("x", [0, -1, 1, -1])


def apply_abs_max(series: pl.Series, default: int) -> int:
    result = series.abs().max()
    if result is None:
        return default
    else:
        if isinstance(result, int):
            return result
        else:
            raise ValueError(f"{result=}, {type(result)=}, expected `int`.")


apply_abs_max(series, -1)
# 1

Suppose I want to generalize apply_abs_max to apply_expr:

import polars as pl

series = pl.Series("x", [0, -1, 1, -1])


def apply_expr(series: pl.Series, default: int, expr: pl.Expr) -> int:
    raise NotImplementedError()
    result = ...  # what do I do here to apply `expr` to `series`?
    if result is None:
        return default
    else:
        if isinstance(result, int):
            return result
        else:
            raise ValueError(f"{result=}, {type(result)=}, expected `int`.")


apply_expr(series, -1, pl.Expr().abs().max())

apply_expr is not actually implemented, as you can see above, because I do not know how to apply the input expr onto series. How can I go about doing that?

1

you always can use anonymous function wrapper:

def apply_expr(series: pl.Series, default: int, expr_func) -> int:
    # raise NotImplementedError()
    result = expr_func(series)
    if result is None:
        return default
    else:
        if isinstance(result, int):
            return result
        else:
            raise ValueError(f"{result=}, {type(result)=}, expected `int`.")


apply_expr(series, -1, lambda x: x.abs().max())

3

You can’t chain the exprs like that. You can do pl.Expr.max but when you put the parenthesis there it’s telling python to call it and you get an error about missing arguments.

Setting that aside for a moment, your function would look like this:

def apply_expr(series: pl.Series, default: int, expr: pl.Expr) -> int:
    result=series.to_frame().select(expr(pl.first())).item() # type: ignore
    if result is None:
        return default
    elif isinstance(result, int):
        return result
    raise ValueError(f"result type is {type(result)}, expected int")

and, with it, you can do:

apply_exprs(series, -1, pl.Expr.abs)

If you want to chain them you’d have to put them in a list so your function becomes…

def apply_exprs(series: pl.Series, default: int, expr: pl.Expr | list[pl.Expr]) -> int:
    if isinstance(expr, list):
        last_expr = expr[-1]
        intermediate_exprs = expr[:-1]
        for e in intermediate_exprs:
            series = series.to_frame().select(e(pl.first())).to_series() # type: ignore
    else:
        last_expr = expr

Before seeing how to use that function, let’s change the series so the output is more obviously what we expect:

series = pl.Series("x", [0, -1, 1, -3])
apply_exprs(series, -1, [pl.Expr.abs,
                        pl.Expr.max])
## 3

But why

When you call an Expr’s method (ie. pl.col('a').abs()) it returns another Expr. Since it’s another Expr, rather than just the method itself, it has all the methods that any Expr has. When you want to refer to the method so that you can pass it to a function, you can’t call it, and because you can’t call it, you can’t chain multiple methods. If you’re not calling it then it’s not returning anything so therefore you can’t chain it either.

You could augment this so that you input something like pl.first().abs().max() instead of pl.Expr.abs which would be better because you could do away with the for loop.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật