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

Fix groupby(as_index=False).size not reseting index #17499

Merged
merged 3 commits into from
Dec 4, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Fix groupby(as_index=False).size not reseting index
  • Loading branch information
mroeschke committed Dec 3, 2024
commit 0cdb823a11933fe41e2d1c26402cf034d0a84b3b
8 changes: 5 additions & 3 deletions python/cudf/cudf/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -497,11 +497,14 @@ def size(self):
col = cudf.core.column.column_empty(
len(self.obj), "int8", masked=False
)
return (
cudf.Series._from_column(col)
result = (
cudf.Series._from_column(col, name=getattr(self.obj, "name", None))
.groupby(self.grouping, sort=self._sort, dropna=self._dropna)
.agg("size")
)
if not self._as_index:
result = result.rename("size").reset_index()
return result

@_performance_tracking
def cumcount(self, ascending: bool = True):
Expand Down Expand Up @@ -803,7 +806,6 @@ def agg(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs):
right_order, len(result), nullify=False
)
)

if not self._as_index:
result = result.reset_index()
if libgroupby._is_all_scan_aggregate(normalized_aggs):
Expand Down
14 changes: 14 additions & 0 deletions python/cudf/cudf/tests/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -4074,3 +4074,17 @@ def test_get_group_list_like():

with pytest.raises(KeyError):
df.groupby(["a"]).get_group([1])


def test_size_as_index_false():
df = pd.DataFrame({"a": [1, 2, 1], "b": [1, 2, 3]}, columns=["a", "b"])
expected = df.groupby("a", as_index=False).size()
result = cudf.from_pandas(df).groupby("a", as_index=False).size()
assert_eq(result, expected)


def test_size_series_with_name():
ser = pd.Series(range(3), name="foo")
expected = ser.groupby(ser).size()
result = cudf.from_pandas(ser).groupby(ser).size()
assert_eq(result, expected)