Skip to content
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

CLN/PERF: Simplify argmin/argmax #58019

Merged
merged 5 commits into from
Apr 1, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 2 additions & 2 deletions pandas/core/arrays/_mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,15 +210,15 @@ def argmin(self, axis: AxisInt = 0, skipna: bool = True): # type: ignore[overri
# override base class by adding axis keyword
validate_bool_kwarg(skipna, "skipna")
if not skipna and self._hasna:
raise NotImplementedError
raise ValueError("Encountered an NA value with skipna=False")
return nargminmax(self, "argmin", axis=axis)

# Signature of "argmax" incompatible with supertype "ExtensionArray"
def argmax(self, axis: AxisInt = 0, skipna: bool = True): # type: ignore[override]
# override base class by adding axis keyword
validate_bool_kwarg(skipna, "skipna")
if not skipna and self._hasna:
raise NotImplementedError
raise ValueError("Encountered an NA value with skipna=False")
return nargminmax(self, "argmax", axis=axis)

def unique(self) -> Self:
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/arrays/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -885,7 +885,7 @@ def argmin(self, skipna: bool = True) -> int:
# 2. argmin itself : total control over sorting.
validate_bool_kwarg(skipna, "skipna")
if not skipna and self._hasna:
raise NotImplementedError
raise ValueError("Encountered an NA value with skipna=False")
return nargminmax(self, "argmin")

def argmax(self, skipna: bool = True) -> int:
Expand Down Expand Up @@ -919,7 +919,7 @@ def argmax(self, skipna: bool = True) -> int:
# 2. argmax itself : total control over sorting.
validate_bool_kwarg(skipna, "skipna")
if not skipna and self._hasna:
raise NotImplementedError
raise ValueError("Encountered an NA value with skipna=False")
return nargminmax(self, "argmax")

def interpolate(
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/arrays/sparse/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -1623,13 +1623,13 @@ def _argmin_argmax(self, kind: Literal["argmin", "argmax"]) -> int:
def argmax(self, skipna: bool = True) -> int:
validate_bool_kwarg(skipna, "skipna")
if not skipna and self._hasna:
raise NotImplementedError
raise ValueError("Encountered an NA value with skipna=False")
return self._argmin_argmax("argmax")

def argmin(self, skipna: bool = True) -> int:
validate_bool_kwarg(skipna, "skipna")
if not skipna and self._hasna:
raise NotImplementedError
raise ValueError("Encountered an NA value with skipna=False")
return self._argmin_argmax("argmin")

# ------------------------------------------------------------------------
Expand Down
33 changes: 3 additions & 30 deletions pandas/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@

from pandas.core import (
algorithms,
nanops,
ops,
)
from pandas.core.accessor import DirNamesMixin
Expand Down Expand Up @@ -731,43 +730,17 @@ def argmax(
the minimum cereal calories is the first element,
since series is zero-indexed.
"""
delegate = self._values
nv.validate_minmax_axis(axis)
skipna = nv.validate_argmax_with_skipna(skipna, args, kwargs)

if skipna and len(delegate) > 0 and isna(delegate).all():
raise ValueError("Encountered all NA values")
elif not skipna and isna(delegate).any():
raise ValueError("Encountered an NA value with skipna=False")

if isinstance(delegate, ExtensionArray):
return delegate.argmax()
else:
result = nanops.nanargmax(delegate, skipna=skipna)
# error: Incompatible return value type (got "Union[int, ndarray]", expected
# "int")
return result # type: ignore[return-value]
return self.array.argmax(skipna=skipna)

@doc(argmax, op="min", oppose="max", value="smallest")
def argmin(
self, axis: AxisInt | None = None, skipna: bool = True, *args, **kwargs
) -> int:
delegate = self._values
nv.validate_minmax_axis(axis)
skipna = nv.validate_argmin_with_skipna(skipna, args, kwargs)

if skipna and len(delegate) > 0 and isna(delegate).all():
raise ValueError("Encountered all NA values")
elif not skipna and isna(delegate).any():
raise ValueError("Encountered an NA value with skipna=False")

if isinstance(delegate, ExtensionArray):
return delegate.argmin()
else:
result = nanops.nanargmin(delegate, skipna=skipna)
# error: Incompatible return value type (got "Union[int, ndarray]", expected
# "int")
return result # type: ignore[return-value]
skipna = nv.validate_argmax_with_skipna(skipna, args, kwargs)
return self.array.argmin(skipna=skipna)

def tolist(self) -> list:
"""
Expand Down
13 changes: 7 additions & 6 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -6976,10 +6976,11 @@ def argmin(self, axis=None, skipna: bool = True, *args, **kwargs) -> int:

if not self._is_multi and self.hasnans:
# Take advantage of cache
if self._isnan.all():
raise ValueError("Encountered all NA values")
elif not skipna:
if not skipna:
raise ValueError("Encountered an NA value with skipna=False")
elif self._isnan.all():
raise ValueError("Encountered all NA values")

return super().argmin(skipna=skipna)

@Appender(IndexOpsMixin.argmax.__doc__)
Expand All @@ -6989,10 +6990,10 @@ def argmax(self, axis=None, skipna: bool = True, *args, **kwargs) -> int:

if not self._is_multi and self.hasnans:
# Take advantage of cache
WillAyd marked this conversation as resolved.
Show resolved Hide resolved
if self._isnan.all():
raise ValueError("Encountered all NA values")
elif not skipna:
if not skipna:
raise ValueError("Encountered an NA value with skipna=False")
elif self._isnan.all():
raise ValueError("Encountered all NA values")
return super().argmax(skipna=skipna)

def min(self, axis=None, skipna: bool = True, *args, **kwargs):
Expand Down
19 changes: 7 additions & 12 deletions pandas/core/nanops.py
Original file line number Diff line number Diff line change
Expand Up @@ -1439,20 +1439,15 @@ def _maybe_arg_null_out(
return result

if axis is None or not getattr(result, "ndim", False):
if skipna:
if mask.all():
raise ValueError("Encountered all NA values")
else:
if mask.any():
raise ValueError("Encountered an NA value with skipna=False")
if skipna and mask.all():
raise ValueError("Encountered all NA values")
elif not skipna and mask.any():
raise ValueError("Encountered an NA value with skipna=False")
else:
na_mask = mask.all(axis)
if na_mask.any():
if skipna and mask.all(axis).any():
raise ValueError("Encountered all NA values")
elif not skipna:
na_mask = mask.any(axis)
if na_mask.any():
raise ValueError("Encountered an NA value with skipna=False")
elif not skipna and mask.any(axis).any():
raise ValueError("Encountered an NA value with skipna=False")
return result


Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/extension/base/methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,10 +191,10 @@ def test_argmax_argmin_no_skipna_notimplemented(self, data_missing_for_sorting):
# GH#38733
data = data_missing_for_sorting

with pytest.raises(NotImplementedError, match=""):
with pytest.raises(ValueError, match="Encountered an NA value"):
data.argmin(skipna=False)

with pytest.raises(NotImplementedError, match=""):
with pytest.raises(ValueError, match="Encountered an NA value"):
data.argmax(skipna=False)

@pytest.mark.parametrize(
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/frame/test_reductions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1066,7 +1066,7 @@ def test_idxmin(self, float_frame, int_frame, skipna, axis):
frame.iloc[15:20, -2:] = np.nan
for df in [frame, int_frame]:
if (not skipna or axis == 1) and df is not int_frame:
if axis == 1:
if skipna:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we still be hitting this with the axis == 1 case?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When axis==1 we run into all NAs for a single row, but when skipna=False we still raise the error message "Encountered an NA value with skipna=False" for performance - see the bottom half of #57971 (comment)

msg = "Encountered all NA values"
else:
msg = "Encountered an NA value"
Expand Down Expand Up @@ -1116,7 +1116,7 @@ def test_idxmax(self, float_frame, int_frame, skipna, axis):
frame.iloc[15:20, -2:] = np.nan
for df in [frame, int_frame]:
if (skipna is False or axis == 1) and df is frame:
if axis == 1:
if skipna:
msg = "Encountered all NA values"
else:
msg = "Encountered an NA value"
Expand Down
29 changes: 17 additions & 12 deletions pandas/tests/reductions/test_reductions.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,9 +171,9 @@ def test_argminmax(self):
obj.argmin()
with pytest.raises(ValueError, match="Encountered all NA values"):
obj.argmax()
with pytest.raises(ValueError, match="Encountered all NA values"):
with pytest.raises(ValueError, match="Encountered an NA value"):
obj.argmin(skipna=False)
with pytest.raises(ValueError, match="Encountered all NA values"):
with pytest.raises(ValueError, match="Encountered an NA value"):
obj.argmax(skipna=False)

obj = Index([NaT, datetime(2011, 11, 1), datetime(2011, 11, 2), NaT])
Expand All @@ -189,9 +189,9 @@ def test_argminmax(self):
obj.argmin()
with pytest.raises(ValueError, match="Encountered all NA values"):
obj.argmax()
with pytest.raises(ValueError, match="Encountered all NA values"):
with pytest.raises(ValueError, match="Encountered an NA value"):
obj.argmin(skipna=False)
with pytest.raises(ValueError, match="Encountered all NA values"):
with pytest.raises(ValueError, match="Encountered an NA value"):
obj.argmax(skipna=False)

@pytest.mark.parametrize("op, expected_col", [["max", "a"], ["min", "b"]])
Expand Down Expand Up @@ -856,7 +856,8 @@ def test_idxmin(self):

# all NaNs
allna = string_series * np.nan
with pytest.raises(ValueError, match="Encountered all NA values"):
msg = "attempt to get argmin of an empty sequence"
with pytest.raises(ValueError, match=msg):
allna.idxmin()

# datetime64[ns]
Expand Down Expand Up @@ -888,7 +889,8 @@ def test_idxmax(self):

# all NaNs
allna = string_series * np.nan
with pytest.raises(ValueError, match="Encountered all NA values"):
msg = "attempt to get argmax of an empty sequence"
with pytest.raises(ValueError, match=msg):
allna.idxmax()

s = Series(date_range("20130102", periods=6))
Expand Down Expand Up @@ -1143,14 +1145,17 @@ def test_idxminmax_object_dtype(self, using_infer_string):
if not using_infer_string:
# attempting to compare np.nan with string raises
ser3 = Series(["foo", "foo", "bar", "bar", None, np.nan, "baz"])
msg = "'>' not supported between instances of 'float' and 'str'"
with pytest.raises(TypeError, match=msg):
ser3.idxmax()
result = ser3.idxmax()
expected = 0
assert result == expected

with pytest.raises(ValueError, match="Encountered an NA value"):
ser3.idxmax(skipna=False)
msg = "'<' not supported between instances of 'float' and 'str'"
with pytest.raises(TypeError, match=msg):
ser3.idxmin()

result = ser3.idxmin()
expected = 2
assert result == expected

with pytest.raises(ValueError, match="Encountered an NA value"):
ser3.idxmin(skipna=False)

Expand Down
Loading