Skip to content

Commit

Permalink
feat(python): Support n expression passed to Expr.head/tail (#8098)
Browse files Browse the repository at this point in the history
  • Loading branch information
josh authored Apr 10, 2023
1 parent e1bf4e7 commit 91a0834
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
11 changes: 6 additions & 5 deletions py-polars/polars/expr/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -3465,7 +3465,7 @@ def take_every(self, n: int) -> Self:
"""
return self._from_pyexpr(self._pyexpr.take_every(n))

def head(self, n: int = 10) -> Self:
def head(self, n: int | Expr = 10) -> Self:
"""
Get the first `n` rows.
Expand All @@ -3490,9 +3490,9 @@ def head(self, n: int = 10) -> Self:
└─────┘
"""
return self._from_pyexpr(self._pyexpr.head(n))
return self.slice(0, n)

def tail(self, n: int = 10) -> Self:
def tail(self, n: int | Expr = 10) -> Self:
"""
Get the last `n` rows.
Expand All @@ -3517,9 +3517,10 @@ def tail(self, n: int = 10) -> Self:
└─────┘
"""
return self._from_pyexpr(self._pyexpr.tail(n))
offset = -expr_to_lit_or_expr(n, str_to_lit=False)
return self.slice(offset, n)

def limit(self, n: int = 10) -> Self:
def limit(self, n: int | Expr = 10) -> Self:
"""
Get the first `n` rows (alias for :func:`Expr.head`).
Expand Down
16 changes: 16 additions & 0 deletions py-polars/tests/unit/test_exprs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1034,3 +1034,19 @@ def test_operators_vs_expressions() -> None:
| (pl.col("y").cast(int) == pl.col("z"))
),
)


def test_head() -> None:
df = pl.DataFrame({"a": [1, 2, 3, 4, 5]})
assert df.select(pl.col("a").head(0)).to_dict(False) == {"a": []}
assert df.select(pl.col("a").head(3)).to_dict(False) == {"a": [1, 2, 3]}
assert df.select(pl.col("a").head(10)).to_dict(False) == {"a": [1, 2, 3, 4, 5]}
assert df.select(pl.col("a").head(pl.count() / 2)).to_dict(False) == {"a": [1, 2]}


def test_tail() -> None:
df = pl.DataFrame({"a": [1, 2, 3, 4, 5]})
assert df.select(pl.col("a").tail(0)).to_dict(False) == {"a": []}
assert df.select(pl.col("a").tail(3)).to_dict(False) == {"a": [3, 4, 5]}
assert df.select(pl.col("a").tail(10)).to_dict(False) == {"a": [1, 2, 3, 4, 5]}
assert df.select(pl.col("a").tail(pl.count() / 2)).to_dict(False) == {"a": [4, 5]}

0 comments on commit 91a0834

Please sign in to comment.