Skip to content

Commit

Permalink
feat[python]: Allow use of builtin abs() (#4650)
Browse files Browse the repository at this point in the history
  • Loading branch information
abalkin committed Sep 1, 2022
1 parent 6c6c8e4 commit 4cd98b3
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 2 deletions.
5 changes: 5 additions & 0 deletions py-polars/polars/internals/expr/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,9 @@ def __bool__(self) -> Expr:
"Hint: use '&' or '|' to chain Expr together, not and/or."
)

def __abs__(self) -> Expr:
return wrap_expr(self._pyexpr.abs())

def __invert__(self) -> Expr:
return self.is_not()

Expand Down Expand Up @@ -4584,6 +4587,8 @@ def abs(self) -> Expr:
"""
Compute absolute values.
Same as `abs(expr)`.
Examples
--------
>>> df = pl.DataFrame(
Expand Down
10 changes: 8 additions & 2 deletions py-polars/polars/internals/series/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
from polars.internals.series.list import ListNameSpace
from polars.internals.series.string import StringNameSpace
from polars.internals.series.struct import StructNameSpace
from polars.internals.series.utils import expr_dispatch, get_ffi_func
from polars.internals.series.utils import call_expr, expr_dispatch, get_ffi_func
from polars.internals.slice import PolarsSlice
from polars.utils import (
_date_to_pl_date,
Expand Down Expand Up @@ -3733,7 +3733,13 @@ def interpolate(self) -> Series:
"""

def abs(self) -> Series:
"""Compute absolute values."""
"""
Compute absolute values.
Same as `abs(series)`.
"""

__abs__ = call_expr(abs)

def rank(self, method: RankMethod = "average", reverse: bool = False) -> Series:
"""
Expand Down
7 changes: 7 additions & 0 deletions py-polars/tests/test_exprs.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,3 +405,10 @@ def test_search_sorted() -> None:

for v in range(int(np.min(a)), int(np.max(a)), 20):
assert np.searchsorted(a, v) == s.search_sorted(v)


def test_abs_expr() -> None:
df = pl.DataFrame({"x": [-1, 0, 1]})
out = df.select(abs(pl.col("x")))

assert out["x"].to_list() == [1, 0, 1]
7 changes: 7 additions & 0 deletions py-polars/tests/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1965,3 +1965,10 @@ class XSeries(pl.Series):
assert "1001" in x_repr
for n in x.to_list():
assert str(n) in x_repr


def test_builtin_abs() -> None:
s = pl.Series("s", [-1, 0, 1, None])
a = abs(s)

assert a.to_list() == [1, 0, 1, None]

0 comments on commit 4cd98b3

Please sign in to comment.