Skip to content

REF: define nanargminmax without values_for_argsort #37815

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 14, 2020
Merged
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
21 changes: 13 additions & 8 deletions pandas/core/sorting.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@

if TYPE_CHECKING:
from pandas import MultiIndex
from pandas.core.arrays import ExtensionArray
from pandas.core.indexes.base import Index

_INT64_MAX = np.iinfo(np.int64).max
Expand Down Expand Up @@ -390,7 +391,7 @@ def nargsort(
return indexer


def nargminmax(values, method: str):
def nargminmax(values: "ExtensionArray", method: str) -> int:
"""
Implementation of np.argmin/argmax but for ExtensionArray and which
handles missing values.
Expand All @@ -405,16 +406,20 @@ def nargminmax(values, method: str):
int
"""
assert method in {"argmax", "argmin"}
func = np.argmax if method == "argmax" else np.argmin

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

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

return non_nan_idx[func(non_nans)]
return sorters[0]


def _ensure_key_mapped_multiindex(
Expand Down