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

Respect groupby.nunique(dropna=False) #16921

Merged
merged 3 commits into from
Sep 26, 2024
Merged
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
7 changes: 5 additions & 2 deletions python/cudf/cudf/_lib/aggregation.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,11 @@ class Aggregation:
)

@classmethod
def nunique(cls):
return cls(pylibcudf.aggregation.nunique(pylibcudf.types.NullPolicy.EXCLUDE))
def nunique(cls, dropna=True):
return cls(pylibcudf.aggregation.nunique(
pylibcudf.types.NullPolicy.EXCLUDE
if dropna else pylibcudf.types.NullPolicy.INCLUDE
))

@classmethod
def nth(cls, size):
Expand Down
16 changes: 16 additions & 0 deletions python/cudf/cudf/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -2232,6 +2232,22 @@ def func(x):

return self.agg(func)

@_performance_tracking
def nunique(self, dropna: bool = True):
"""
Return number of unique elements in the group.

Parameters
----------
dropna : bool, default True
Don't include NaN in the counts.
"""

def func(x):
return getattr(x, "nunique")(dropna=dropna)

return self.agg(func)

@_performance_tracking
def std(
self,
Expand Down
17 changes: 17 additions & 0 deletions python/cudf/cudf/tests/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -1940,6 +1940,23 @@ def test_groupby_nunique(agg, by):
assert_groupby_results_equal(expect, got, check_dtype=False)


@pytest.mark.parametrize("dropna", [True, False])
def test_nunique_dropna(dropna):
gdf = cudf.DataFrame(
{
"a": [1, 1, 2],
"b": [4, None, 5],
"c": [None, None, 7],
"d": [1, 1, 3],
}
)
pdf = gdf.to_pandas()

result = gdf.groupby("a")["b"].nunique(dropna=dropna)
expected = pdf.groupby("a")["b"].nunique(dropna=dropna)
assert_groupby_results_equal(result, expected, check_dtype=False)


@pytest.mark.parametrize(
"n",
[0, 1, 2, 10],
Expand Down
Loading