31
31
32
32
if TYPE_CHECKING :
33
33
from pandas import MultiIndex
34
+ from pandas .core .arrays import ExtensionArray
34
35
from pandas .core .indexes .base import Index
35
36
36
37
_INT64_MAX = np .iinfo (np .int64 ).max
@@ -390,7 +391,7 @@ def nargsort(
390
391
return indexer
391
392
392
393
393
- def nargminmax (values , method : str ):
394
+ def nargminmax (values : "ExtensionArray" , method : str ) -> int :
394
395
"""
395
396
Implementation of np.argmin/argmax but for ExtensionArray and which
396
397
handles missing values.
@@ -405,16 +406,20 @@ def nargminmax(values, method: str):
405
406
int
406
407
"""
407
408
assert method in {"argmax" , "argmin" }
408
- func = np .argmax if method == "argmax" else np .argmin
409
409
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" )
412
414
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 )
416
421
417
- return non_nan_idx [ func ( non_nans ) ]
422
+ return sorters [ 0 ]
418
423
419
424
420
425
def _ensure_key_mapped_multiindex (
0 commit comments