From f90773679c9cfcd49d660f17740b1451dc857b8a Mon Sep 17 00:00:00 2001 From: hussainsultan Date: Fri, 11 Mar 2022 11:35:35 -0500 Subject: [PATCH] feat(api): add `ibis.asc` expression --- ibis/expr/api.py | 26 ++++++++++++++++++++++++++ ibis/tests/expr/test_table.py | 15 +++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/ibis/expr/api.py b/ibis/expr/api.py index 7a6faf6a35d7..3f15e99a9d72 100644 --- a/ibis/expr/api.py +++ b/ibis/expr/api.py @@ -118,6 +118,7 @@ 'cumulative_window', 'date', 'desc', + 'asc', 'Expr', 'geo_area', 'geo_as_binary', @@ -347,6 +348,31 @@ def desc(expr: ir.ColumnExpr | str) -> ir.SortExpr | ops.DeferredSortKey: return ops.SortKey(expr, ascending=False).to_expr() +def asc(expr: ir.ColumnExpr | str) -> ir.SortExpr | ops.DeferredSortKey: + """Create a ascending sort key from `asc` or column name. + + Parameters + ---------- + expr + The expression or column name to use for sorting + + Examples + -------- + >>> import ibis + >>> t = ibis.table([('g', 'string')]) + >>> result = t.group_by('g').size('count').sort_by(ibis.asc('count')) + + Returns + ------- + ops.DeferredSortKey + A deferred sort key + """ + if not isinstance(expr, Expr): + return ops.DeferredSortKey(expr) + else: + return ops.SortKey(expr).to_expr() + + def timestamp( value: str | numbers.Integral, timezone: str | None = None, diff --git a/ibis/tests/expr/test_table.py b/ibis/tests/expr/test_table.py index 78701f7a73f1..3dedbceca8a4 100644 --- a/ibis/tests/expr/test_table.py +++ b/ibis/tests/expr/test_table.py @@ -386,6 +386,17 @@ def test_sort_by_desc_deferred_sort_key(table): assert_equal(result, expected2) +def test_sort_by_asc_deferred_sort_key(table): + result = table.group_by('g').size().sort_by(ibis.asc('count')) + + tmp = table.group_by('g').size() + expected = tmp.sort_by(tmp['count']) + expected2 = tmp.sort_by(ibis.asc(tmp['count'])) + + assert_equal(result, expected) + assert_equal(result, expected2) + + def test_slice_convenience(table): expr = table[:5] expr2 = table[:5:1] @@ -1218,6 +1229,10 @@ def test_sort_by2(table): result = m.sort_by(ibis.desc(lambda x: x.foo)) expected = m.sort_by(ibis.desc('foo')) assert_equal(result, expected) + + result = m.sort_by(ibis.asc(lambda x: x.foo)) + expected = m.sort_by('foo') + assert_equal(result, expected) def test_projection2(table):