Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 43 additions & 21 deletions python/pyarrow/compute.py
Original file line number Diff line number Diff line change
Expand Up @@ -567,6 +567,35 @@ def fill_null(values, fill_value):
return call_function("coalesce", [values, fill_value])


def _select_k_sort_keys(values, sort_keys, null_placements, order):
if isinstance(sort_keys, str) or isinstance(null_placements, str):
raise TypeError(
"sort_keys and null_placements must be list-like, not str")

if isinstance(values, (pa.Array, pa.ChunkedArray)):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Array-like inputs like lists silently accept sort_keys but checking for table-like inputs instead would fix this:

Suggested change
if isinstance(values, (pa.Array, pa.ChunkedArray)):
if not isinstance(values, (pa.Table, pa.RecordBatch)):

Without the fix such example incorrectly succeeds:

import pyarrow.compute as pc
pc.top_k_unstable([1, 2, None, 0], 2, sort_keys=["a"])

And this example fails but shouldn't:

pc.top_k_unstable([1, 2, None, 0], k=2)
# pyarrow.lib.ArrowInvalid: select_k_unstable requires a non-empty `sort_keys`

if sort_keys is not None:
raise ValueError(
"sort_keys is only supported for table-like input")
if null_placements is None:
Comment on lines +571 to +579

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One more edge case which produces TypeError instead of ValueError

import pyarrow as pa
import pyarrow.compute as pc
pc.top_k_unstable(pa.array([1, 2, None, 0]), k=2, sort_keys="a")

TypeError: sort_keys and null_placements must be list-like, not str

This can be fixed by reordering these checks like so:

diff --git a/python/pyarrow/compute.py b/python/pyarrow/compute.py
@@ -568,14 +568,18 @@ def fill_null(values, fill_value):
 
 
 def _select_k_sort_keys(values, sort_keys, null_placements, order):
-    if isinstance(sort_keys, str) or isinstance(null_placements, str):
+    is_array_like = not isinstance(values, (pa.Table, pa.RecordBatch))
+    if is_array_like and sort_keys is not None:
+        raise ValueError(
+            "sort_keys is only supported for table-like input")
+
+    if (isinstance(sort_keys, (str, bytes)) or
+            isinstance(null_placements, (str, bytes))):
         raise TypeError(
-            "sort_keys and null_placements must be list-like, not str")
+            "sort_keys and null_placements must be list-like, "
+            "not str or bytes")
 
-    if isinstance(values, (pa.Array, pa.ChunkedArray)):
-        if sort_keys is not None:
-            raise ValueError(
-                "sort_keys is only supported for table-like input")
+    if is_array_like:
         if null_placements is None:
             return [("dummy", order, "at_end")]

... which results in correct ValueError: sort_keys is only supported for table-like input

Plus extra check on (str, bytes) prevents second edge case b"a" from becoming column indices ([97]).

return [("dummy", order, "at_end")]
else:
null_placements = list(null_placements)
if len(null_placements) != 1:
raise ValueError(
"null_placements must have one element for array input")
return [("dummy", order, null_placements[0])]

sort_keys = list(sort_keys) if sort_keys is not None else []
if null_placements is None:
null_placements = ["at_end"] * len(sort_keys)
else:
null_placements = list(null_placements)
if len(null_placements) != len(sort_keys):
raise ValueError(
"sort_keys and null_placements must have the same length")
return [(key, order, null_placements[i]) for i, key in enumerate(sort_keys)]


def top_k_unstable(
values, k, sort_keys=None, null_placements=None, *, memory_pool=None):
"""
Expand All @@ -584,9 +613,11 @@ def top_k_unstable(
The number of `k` elements to keep.
sort_keys : List-like

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sort_keys here and in bottom_k_unstable could be indicated as optional and field references mentioned for clarity.

    sort_keys : List-like, optional
        Column names or field references to order by when input is table-like
        data. Required for table-like input. Not supported for array-like input.

Column key names to order by when input is table-like data.
null_placements : A list of "at_start" or "at_end"
Whether nulls and NaNs are placed at the start or at the end.
Accepted values are "at_end", "at_start".
Not supported for array-like input.
null_placements : List-like of "at_start" or "at_end", optional
Whether nulls and NaNs are placed at the start or at the end,
for each key in `sort_keys` or single element for array input.
If not passed, "at_end" is used for every key.
memory_pool : MemoryPool, optional
If not passed, will allocate memory from the default memory pool.

Expand All @@ -608,13 +639,8 @@ def top_k_unstable(
2
]
"""
if sort_keys is None:
sort_keys = []
if isinstance(values, (pa.Array, pa.ChunkedArray)):
sort_keys.append(("dummy", "descending", "at_end"))
else:
sort_keys = [(sort_key, "descending", null_placement)
for sort_key, null_placement in zip(sort_keys, null_placements)]
sort_keys = _select_k_sort_keys(
values, sort_keys, null_placements, "descending")
options = SelectKOptions(k, sort_keys)
return call_function("select_k_unstable", [values], options, memory_pool)

Expand All @@ -636,9 +662,11 @@ def bottom_k_unstable(
The number of `k` elements to keep.
sort_keys : List-like
Column key names to order by when input is table-like data.
null_placements : A list of "at_start" or "at_end"
Whether nulls and NaNs are placed at the start or at the end.
Accepted values are "at_end", "at_start".
Not supported for array-like input.
null_placements : List-like of "at_start" or "at_end", optional
Whether nulls and NaNs are placed at the start or at the end,
for each key in `sort_keys` or single element for array input.
If not passed, "at_end" is used for every key.
memory_pool : MemoryPool, optional
If not passed, will allocate memory from the default memory pool.

Expand All @@ -660,14 +688,8 @@ def bottom_k_unstable(
2
]
"""
if sort_keys is None:
sort_keys = []
if isinstance(values, (pa.Array, pa.ChunkedArray)):
sort_keys.append(("dummy", "ascending", "at_end"))
else:
sort_keys = [(sort_key, "ascending", null_placement)
for sort_key, null_placement in zip(sort_keys, null_placements)]

sort_keys = _select_k_sort_keys(
values, sort_keys, null_placements, "ascending")
options = SelectKOptions(k, sort_keys)
return call_function("select_k_unstable", [values], options, memory_pool)

Expand Down
34 changes: 34 additions & 0 deletions python/pyarrow/tests/test_compute.py
Original file line number Diff line number Diff line change
Expand Up @@ -3251,6 +3251,40 @@ def validate_select_k(select_k_indices, tbl, sort_keys, stable_sort=False):
pc.select_k_unstable(table, k=k, sort_keys=[("unknown", "ascending", "at_end")])


def test_top_k_bottom_k_():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def test_top_k_bottom_k_():
def test_top_k_bottom_k():

Typo?

arr = pa.array([1, 2, None, 0])
table = pa.table({"a": [1, 2, None], "b": [None, 0, 1]})

# null_placements defaults to "at_end" for every key
assert pc.top_k_unstable(table, k=2, sort_keys=["a"]).to_pylist() == [1, 0]
Comment thread
tadeja marked this conversation as resolved.
Resolved
assert pc.bottom_k_unstable(
table, k=2, sort_keys=("a", "b")).to_pylist() == [0, 1]

# null_placements "at_start" is not ignored for array input
assert pc.top_k_unstable(arr, k=2, null_placements=[
"at_start"]).to_pylist() == [2, 1]
assert pc.bottom_k_unstable(arr, k=2, null_placements=[
"at_start"]).to_pylist() == [2, 3]

for func in [pc.top_k_unstable, pc.bottom_k_unstable]:
sort_keys = ["a"]
with pytest.raises(ValueError, match="only supported for table-like"):
func(arr, k=2, sort_keys=sort_keys)
with pytest.raises(ValueError, match="must have one element"):
func(arr, k=2, null_placements=["at_start", "at_end"])
with pytest.raises(TypeError, match="must be list-like, not str"):
func(arr, k=2, null_placements="at_start")
with pytest.raises(TypeError, match="'int' object is not iterable"):
func(arr, k=2, null_placements=1)
assert sort_keys == ["a"] # list is not mutated
with pytest.raises(TypeError, match="must be list-like"):
func(table, k=2, sort_keys="a")
with pytest.raises(TypeError, match="must be list-like"):
func(table, k=2, sort_keys=["a"], null_placements="at_end")
with pytest.raises(ValueError, match="same length"):
func(table, k=2, sort_keys=["a", "b"], null_placements=["at_end"])


def test_array_sort_indices():
arr = pa.array([1, 2, None, 0])
result = pc.array_sort_indices(arr)
Expand Down
Loading