Skip to content

Commit 698d3dd

Browse files
algos.kth_smallest
1 parent 3f0e9fb commit 698d3dd

File tree

3 files changed

+33
-29
lines changed

3 files changed

+33
-29
lines changed

pandas/_libs_numba/algos.py

+30-28
Original file line numberDiff line numberDiff line change
@@ -230,34 +230,36 @@
230230
# return result, counts
231231

232232

233-
# @cython.boundscheck(False)
234-
# @cython.wraparound(False)
235-
# def kth_smallest(numeric[:] a, Py_ssize_t k) -> numeric:
236-
# cdef:
237-
# Py_ssize_t i, j, l, m, n = a.shape[0]
238-
# numeric x
239-
240-
# with nogil:
241-
# l = 0
242-
# m = n - 1
243-
244-
# while l < m:
245-
# x = a[k]
246-
# i = l
247-
# j = m
248-
249-
# while 1:
250-
# while a[i] < x: i += 1
251-
# while x < a[j]: j -= 1
252-
# if i <= j:
253-
# swap(&a[i], &a[j])
254-
# i += 1; j -= 1
255-
256-
# if i > j: break
257-
258-
# if j < k: l = i
259-
# if k < i: m = j
260-
# return a[k]
233+
@numba.njit
234+
def kth_smallest(a: np.ndarray, k):
235+
n = a.shape[0]
236+
237+
l = 0
238+
m = n - 1
239+
240+
while l < m:
241+
x = a[k]
242+
i = l
243+
j = m
244+
245+
while 1:
246+
while a[i] < x:
247+
i += 1
248+
while x < a[j]:
249+
j -= 1
250+
if i <= j:
251+
a[i], a[j] = a[j], a[i]
252+
i += 1
253+
j -= 1
254+
255+
if i > j:
256+
break
257+
258+
if j < k:
259+
l = i
260+
if k < i:
261+
m = j
262+
return a[k]
261263

262264

263265
# # ----------------------------------------------------------------------

pandas/core/algorithms.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
iNaT,
2929
lib,
3030
)
31+
from pandas._libs_numba import algos as algos_numba
3132
from pandas._typing import (
3233
AnyArrayLike,
3334
ArrayLike,
@@ -1290,7 +1291,7 @@ def compute(self, method: str) -> Series:
12901291
narr = len(arr)
12911292
n = min(n, narr)
12921293

1293-
kth_val = algos.kth_smallest(arr.copy(), n - 1)
1294+
kth_val = algos_numba.kth_smallest(arr.copy(), n - 1)
12941295
(ns,) = np.nonzero(arr <= kth_val)
12951296
inds = ns[arr[ns].argsort(kind="mergesort")]
12961297

setup.cfg

+1
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ ignore =
7676
W504, # line break after binary operator
7777
E402, # module level import not at top of file
7878
E731, # do not assign a lambda expression, use a def
79+
E741, # ambiguous variable name
7980
S001 # found modulo formatter (incorrect picks up mod operations)
8081
exclude =
8182
doc/sphinxext/*.py,

0 commit comments

Comments
 (0)