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 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions pandas/core/arrays/_mixins.py
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
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
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
12 changes: 0 additions & 12 deletions pandas/core/base.py
Expand Up @@ -733,12 +733,6 @@ def argmax(
"""
delegate = self._values
Copy link
Member Author

Choose a reason for hiding this comment

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

Without using the delegate here and the nanops.nanargmax branch below, I'm seeing a 50x perf regression in some ASVs, e.g. series_methods.NanOps.time_func('argmax', 1000000, 'int8'):

N = 1000000
dtype = 'int8'
s = Series(np.ones(N), dtype=dtype)
s.argmax()

@jbrockmendel - perhaps that branch should be deeper in the code where the argmin/argmax implementation is for EAs?

Copy link
Member

Choose a reason for hiding this comment

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

Do you mean if you do return return self.array.argmax(skipna=skipna) without the EA check?

It looks like sorting.nanargminmax is just a lot slower than the nanops.arg(min|max). Best case would be to improve sorting.nanargminmax, but failing that I think making NumpyExtensionArray.argmax call the faster version would be viable (need to double-check they are behaviorally equivalent)

Copy link
Member Author

Choose a reason for hiding this comment

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

Do you mean if you do return return self.array.argmax(skipna=skipna) without the EA check?

Correct.

Best case would be to improve sorting.nanargminmax, but failing that I think making NumpyExtensionArray.argmax call the faster version would be viable

Thanks - will give these a shot.

Copy link
Member Author

Choose a reason for hiding this comment

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

Looked into this, and I don't think either is viable. The main reason nanops.nanargmax is faster than sorting.nanargminmax is that the former only works for numeric dtypes by filling in NA values where appropriate (typically with -np.inf) whereas for EAs (e.g. StringArray) we need to perform indexing operations to remove NA values from any consideration since there is no equivalent of -np.inf I think.

Copy link
Member

Choose a reason for hiding this comment

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

bummer. thanks for takinga look

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()
Expand All @@ -754,12 +748,6 @@ def argmin(
) -> 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()
Expand Down
15 changes: 7 additions & 8 deletions pandas/core/indexes/base.py
Expand Up @@ -6975,11 +6975,11 @@ def argmin(self, axis=None, skipna: bool = True, *args, **kwargs) -> int:
nv.validate_minmax_axis(axis)

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 @@ -6988,11 +6988,10 @@ def argmax(self, axis=None, skipna: bool = True, *args, **kwargs) -> int:
nv.validate_minmax_axis(axis)

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().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
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
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
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
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