diff --git a/pandas/core/methods/selectn.py b/pandas/core/methods/selectn.py index 894791cb46371..843c54de25bc9 100644 --- a/pandas/core/methods/selectn.py +++ b/pandas/core/methods/selectn.py @@ -139,7 +139,8 @@ def compute(self, method: str) -> Series: # arr passed into kth_smallest must be contiguous. We copy # here because kth_smallest will modify its input - kth_val = libalgos.kth_smallest(arr.copy(order="C"), n - 1) + # avoid OOB access with kth_smallest_c when n <= 0 + kth_val = libalgos.kth_smallest(arr.copy(order="C"), max(n - 1, 0)) (ns,) = np.nonzero(arr <= kth_val) inds = ns[arr[ns].argsort(kind="mergesort")]