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 5 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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.0.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ Fixed regressions
Bug fixes
~~~~~~~~~

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

.. ---------------------------------------------------------------------------
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
30 changes: 28 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,31 @@ 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):
strings = ["x", "y", "z"]
arr = pd.Series(strings, dtype="string")
ser = pd.Series(strings)

result = getattr(arr, func)(skipna=skipna)
expected = getattr(ser, func)(skipna=skipna)

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
arr = pd.Series([pd.NA, "y", "z"], dtype="string")
ser = pd.Series(["y", "z"])

result = getattr(arr, func)(skipna=skipna)

if skipna:
expected = getattr(ser, func)()
assert result == expected
else:
assert result is pd.NA