Skip to content

ENH: Implement StringArray.min / max #33351

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 19 commits into from
Apr 25, 2020
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,7 @@ Strings
^^^^^^^

- Bug in the :meth:`~Series.astype` method when converting "string" dtype data to nullable integer dtype (:issue:`32450`).
- Fixed issue where taking ``min`` or ``max`` of a ``StringArray`` or ``Series`` with ``StringDtype`` type would raise. (:issue:`31746`)
-


Expand Down
16 changes: 16 additions & 0 deletions pandas/core/arrays/string_.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

from pandas import compat
from pandas.core import ops
from pandas.core.array_algos import masked_reductions
from pandas.core.arrays import IntegerArray, PandasArray
from pandas.core.arrays.integer import _IntegerDtype
from pandas.core.construction import extract_array
Expand Down Expand Up @@ -282,8 +283,23 @@ def astype(self, dtype, copy=True):
return super().astype(dtype, copy)

def _reduce(self, name, skipna=True, **kwargs):
if name in ["min", "max"]:
return getattr(self, name)(skipna=skipna, **kwargs)

raise TypeError(f"Cannot perform reduction '{name}' with string dtype")

def min(self, axis=None, out=None, keepdims=False, skipna=True):
Copy link
Member

Choose a reason for hiding this comment

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

Is it possible to move all of axis, out and keepdims into **kwargs ? (will need to test with numpy)

This should probably also validate those keywords, if we want to accept them (and we should also test this if we are adding them)

Copy link
Member Author

Choose a reason for hiding this comment

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

Updated, assuming by test with numpy you mean the validation functions in /compat/numpy/function?

Copy link
Member

Choose a reason for hiding this comment

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

Yes, indeed, those validation functions can be used to check additional keywords.

In addition, we should also test this in the tests (so test that np.min(a) works, because that is the only reason we would add those keywords)

result = masked_reductions.min(
values=self.to_numpy(na_value=np.nan), mask=self.isna(), skipna=skipna
)
return result

def max(self, axis=None, out=None, keepdims=False, skipna=True):
result = masked_reductions.max(
values=self.to_numpy(na_value=np.nan), mask=self.isna(), skipna=skipna
)
return result

def value_counts(self, dropna=False):
from pandas import value_counts

Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/arrays/string_/test_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,18 @@ def test_reduce(skipna):
assert result == "abc"


@pytest.mark.parametrize("method", ["min", "max"])
@pytest.mark.parametrize("skipna", [True, False])
def test_min_max(method, skipna):
arr = pd.Series(["a", "b", "c", None], dtype="string")
result = getattr(arr, method)(skipna=skipna)
if skipna:
expected = "a" if method == "min" else "c"
assert result == expected
else:
assert result is pd.NA


@pytest.mark.parametrize("skipna", [True, False])
@pytest.mark.xfail(reason="Not implemented StringArray.sum")
def test_reduce_missing(skipna):
Expand Down
7 changes: 7 additions & 0 deletions pandas/tests/extension/base/reduce.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@ class BaseNoReduceTests(BaseReduceTests):

@pytest.mark.parametrize("skipna", [True, False])
def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna):
if isinstance(data, pd.arrays.StringArray) and all_numeric_reductions in [
Copy link
Contributor

Choose a reason for hiding this comment

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

hmm, @TomAugspurger, @jbrockmendel is this the pattern we are using here for skips like this?

Copy link
Member

Choose a reason for hiding this comment

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

in indexes tests when we have a "this is tested in this other place" comment we usually return/pass instead of pytest.skip.

It's not a perfect system, but I think of it as a way of distinguishing between "this test is skipped but would be nice to enable" vs "nothing to see here"

Copy link
Contributor

Choose a reason for hiding this comment

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

Returning None rather than skipping also keeps the test output cleaner, since we print skipped tests.

Copy link
Member

Choose a reason for hiding this comment

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

We typically refine this for a specific type by overriding this test to have custom behaviour in extension/test_strings.py

Copy link
Contributor

Choose a reason for hiding this comment

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

ok on the test names? @jorisvandenbossche

Copy link
Member

Choose a reason for hiding this comment

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

@dsaxton can you move this special case for string to test_strings.py ? (and there you an override this test method, to do the correct thing for string dtype)

"min",
"max",
]:
# Tested in pandas/tests/arrays/string_/test_string.py
pytest.skip("These reductions are implemented")

op_name = all_numeric_reductions
s = pd.Series(data)

Expand Down