Skip to content

BUG: groupby-nunique modifies null values #31973

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

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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 @@ -19,7 +19,7 @@ Fixed regressions
- Fixed regression in :meth:`Series.align` when ``other`` is a DataFrame and ``method`` is not None (:issue:`31785`)
- Fixed regression in :meth:`pandas.core.groupby.RollingGroupby.apply` where the ``raw`` parameter was ignored (:issue:`31754`)
- Fixed regression in :meth:`rolling(..).corr() <pandas.core.window.Rolling.corr>` when using a time offset (:issue:`31789`)
-
- Fixed regression in :meth:`DataFrameGroupBy.nunique` which was modifying the original values if ``NaN`` values were present (:issue:`31950`)

.. ---------------------------------------------------------------------------

Expand Down
24 changes: 14 additions & 10 deletions pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -591,20 +591,24 @@ def nunique(self, dropna: bool = True) -> Series:

val = self.obj._internal_get_values()

# GH 27951
# temporary fix while we wait for NumPy bug 12629 to be fixed
val[isna(val)] = np.datetime64("NaT")

try:
sorter = np.lexsort((val, ids))
except TypeError: # catches object dtypes
msg = f"val.dtype must be object, got {val.dtype}"
assert val.dtype == object, msg
def _object_sorter(val, ids):
val, _ = algorithms.factorize(val, sort=False)
sorter = np.lexsort((val, ids))
_isna = lambda a: a == -1
return val, sorter, _isna

if isna(val).any() and val.dtype == object:
# Deal with pandas.NaT
val, sorter, _isna = _object_sorter(val, ids)
else:
_isna = isna
try:
sorter = np.lexsort((val, ids))
except TypeError: # catches object dtypes
msg = f"val.dtype must be object, got {val.dtype}"
assert val.dtype == object, msg
val, sorter, _isna = _object_sorter(val, ids)
else:
_isna = isna

ids, val = ids[sorter], val[sorter]

Expand Down
2 changes: 2 additions & 0 deletions pandas/tests/groupby/test_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -966,6 +966,7 @@ def test_frame_describe_unstacked_format():
@pytest.mark.parametrize("dropna", [False, True])
def test_series_groupby_nunique(n, m, sort, dropna):
def check_nunique(df, keys, as_index=True):
original_df = df.copy()
gr = df.groupby(keys, as_index=as_index, sort=sort)
left = gr["julie"].nunique(dropna=dropna)

Expand All @@ -975,6 +976,7 @@ def check_nunique(df, keys, as_index=True):
right = right.reset_index(drop=True)

tm.assert_series_equal(left, right, check_names=False)
tm.assert_frame_equal(df, original_df)

days = date_range("2015-08-23", periods=10)

Expand Down