Skip to content

Commit 840c142

Browse files
authored
REF: define nanargminmax without values_for_argsort (#37815)
1 parent 3c23e6e commit 840c142

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

pandas/core/sorting.py

+13-8
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131

3232
if TYPE_CHECKING:
3333
from pandas import MultiIndex
34+
from pandas.core.arrays import ExtensionArray
3435
from pandas.core.indexes.base import Index
3536

3637
_INT64_MAX = np.iinfo(np.int64).max
@@ -390,7 +391,7 @@ def nargsort(
390391
return indexer
391392

392393

393-
def nargminmax(values, method: str):
394+
def nargminmax(values: "ExtensionArray", method: str) -> int:
394395
"""
395396
Implementation of np.argmin/argmax but for ExtensionArray and which
396397
handles missing values.
@@ -405,16 +406,20 @@ def nargminmax(values, method: str):
405406
int
406407
"""
407408
assert method in {"argmax", "argmin"}
408-
func = np.argmax if method == "argmax" else np.argmin
409409

410-
mask = np.asarray(isna(values))
411-
values = values._values_for_argsort()
410+
mask = np.asarray(values.isna())
411+
if mask.all():
412+
# Use same exception message we would get from numpy
413+
raise ValueError(f"attempt to get {method} of an empty sequence")
412414

413-
idx = np.arange(len(values))
414-
non_nans = values[~mask]
415-
non_nan_idx = idx[~mask]
415+
if method == "argmax":
416+
# Use argsort with ascending=False so that if more than one entry
417+
# achieves the maximum, we take the first such occurence.
418+
sorters = values.argsort(ascending=False)
419+
else:
420+
sorters = values.argsort(ascending=True)
416421

417-
return non_nan_idx[func(non_nans)]
422+
return sorters[0]
418423

419424

420425
def _ensure_key_mapped_multiindex(

0 commit comments

Comments
 (0)