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

Implement some reductions for string Series #31757

Closed
wants to merge 30 commits into from
Closed
Show file tree
Hide file tree
Changes from 8 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
5 changes: 5 additions & 0 deletions doc/source/whatsnew/v1.0.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ Fixed regressions
Bug fixes
~~~~~~~~~

**ExtensionArray**
Copy link
Contributor

Choose a reason for hiding this comment

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

this is likely too invasive for 1.02, move to 1.1


- Fixed issue where taking the minimum, maximum, or sum of a ``Series`` with ``StringDtype`` type would raise. (:issue:`31746`)
-

**I/O**

- Using ``pd.NA`` with :meth:`DataFrame.to_json` now correctly outputs a null value instead of an empty object (:issue:`31615`)
Expand Down
11 changes: 10 additions & 1 deletion pandas/core/arrays/string_.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,16 @@ def astype(self, dtype, copy=True):
return super().astype(dtype, copy)

def _reduce(self, name, skipna=True, **kwargs):
raise TypeError(f"Cannot perform reduction '{name}' with string dtype")
if name in ["min", "max", "sum"]:
na_mask = isna(self)
Copy link
Contributor

Choose a reason for hiding this comment

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

the masking should be done inside the methods themselves, _reduce just dispatches

Copy link
Member Author

Choose a reason for hiding this comment

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

Should we implement these methods for StringArray in that case? The NA handling for PandasArray seems to be broken for string inputs, so it might have to get handled within each method

Copy link
Member

@jorisvandenbossche jorisvandenbossche Feb 13, 2020

Choose a reason for hiding this comment

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

Yes, I would say don't care about PandasArray too much (since PandasArray is not using pd.NA), and just implement the methods here on StringArray.

Copy link
Member Author

Choose a reason for hiding this comment

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

I think the reason why the NA-handling wasn't working was due to an apparently long-standing bug in nanops.nanminmax which I think we can fix here: #18588. Basically we are filling NA with infinite values when taking the min or max, but this doesn't make sense for object dtypes and an error gets raised even if skipna is True.

If we fix that by explicitly masking the missing values instead, I believe we can just use this function directly in StringArray methods.

if not na_mask.any():
return getattr(self, name)(skipna=False, **kwargs)
elif skipna:
return getattr(self[~na_mask], name)(skipna=False, **kwargs)
else:
return libmissing.NA
else:
dsaxton marked this conversation as resolved.
Show resolved Hide resolved
raise TypeError(f"Cannot perform reduction '{name}' with string dtype")

def value_counts(self, dropna=False):
from pandas import value_counts
Expand Down
25 changes: 23 additions & 2 deletions pandas/tests/arrays/string_/test_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,15 +215,13 @@ def test_from_sequence_no_mutate(copy):


@pytest.mark.parametrize("skipna", [True, False])
@pytest.mark.xfail(reason="Not implemented StringArray.sum")
def test_reduce(skipna):
arr = pd.Series(["a", "b", "c"], dtype="string")
result = arr.sum(skipna=skipna)
assert result == "abc"


@pytest.mark.parametrize("skipna", [True, False])
@pytest.mark.xfail(reason="Not implemented StringArray.sum")
def test_reduce_missing(skipna):
arr = pd.Series([None, "a", None, "b", "c", None], dtype="string")
result = arr.sum(skipna=skipna)
Expand Down Expand Up @@ -269,3 +267,26 @@ def test_value_counts_na():
result = arr.value_counts(dropna=True)
expected = pd.Series([2, 1], index=["a", "b"], dtype="Int64")
tm.assert_series_equal(result, expected)


@pytest.mark.parametrize("func", ["min", "max"])
@pytest.mark.parametrize("skipna", [True, False])
def test_reduction(func, skipna):
jreback marked this conversation as resolved.
Show resolved Hide resolved
s = pd.Series(["x", "y", "z"], dtype="string")
result = getattr(s, func)(skipna=skipna)
expected = "x" if func == "min" else "z"

assert result == expected
jorisvandenbossche marked this conversation as resolved.
Show resolved Hide resolved


@pytest.mark.parametrize("func", ["min", "max"])
@pytest.mark.parametrize("skipna", [True, False])
def test_reduction_with_na(func, skipna):
dsaxton marked this conversation as resolved.
Show resolved Hide resolved
s = pd.Series([pd.NA, "y", "z"], dtype="string")
result = getattr(s, func)(skipna=skipna)

if skipna:
expected = "y" if func == "min" else "z"
assert result == expected
else:
assert result is pd.NA
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 [
"min",
"max",
"sum",
]:
pytest.skip("These reductions are implemented")
Copy link
Member

Choose a reason for hiding this comment

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

Can you see if you can rather update this in test_string.py ? It might be we now need to subclass the ReduceTests instead of NoReduceTests.
(ideally the base tests remain dtype agnostic)

Copy link
Member Author

Choose a reason for hiding this comment

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

By updating in test_string.py do you mean adding tests using the fixtures data and all_numeric_reductions, only checking for the "correct" output (and skipping over those reductions that aren't yet implemented)?

Copy link
Member

Choose a reason for hiding this comment

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

Hmm, actually looking at the base reduction tests now: they are not really written in a way that they will pass for strings.

But so you can copy this test to tests/extension/test_strings.py (and so override the base one), and then do the string-array-specific adaptation there. It gives some duplication of the test code, but it's not long, and it clearer separation of concerns (the changes for string array are in test_string)

Copy link
Member Author

Choose a reason for hiding this comment

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

Ok, so we can remove the special cases for StringArray in BaseNoReduceTests without getting test failures, as long as they're handled in TestNoReduce in test_string.py? I'm not too familiar with how these particular tests actually get executed during CI


op_name = all_numeric_reductions
s = pd.Series(data)

Expand Down