Skip to content

fix #3141 add cumsum to DatasetGroupBy #3417

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 1 commit 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
1 change: 1 addition & 0 deletions xarray/core/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -859,3 +859,4 @@ def assign(self, **kwargs):

ops.inject_reduce_methods(DatasetGroupBy)
ops.inject_binary_ops(DatasetGroupBy)
ops.inject_cum_methods(DatasetGroupBy)
17 changes: 17 additions & 0 deletions xarray/tests/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,4 +202,21 @@ def test_da_groupby_assign_coords():
assert_identical(expected, actual2)


def test_da_groupby_cumsum():
ds = xr.Dataset(
{"foo": (("x",), [7, 3, 1, 1, 1, 1, 1])},
coords={"x": [0, 1, 2, 3, 4, 5, 6], "group_id": ("x", [0, 0, 1, 1, 2, 2, 2])},
)
actual = ds.groupby("group_id").cumsum(dim="x")
expected = xr.Dataset(
{
"foo": (("x",), [7, 10, 1, 2, 1, 2, 3]),
"group_id": (("x",), [0, 0, 1, 1, 2, 2, 2]),
Copy link
Collaborator

Choose a reason for hiding this comment

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

Any idea why group_id becomes a data variable rather than a coord?

Here's the equivalent with sum:

In [6]: ds.groupby("group_id").sum()
Out[6]:
<xarray.Dataset>
Dimensions:   (group_id: 3)
Coordinates:
  * group_id  (group_id) int64 0 1 2
Data variables:
    foo       (group_id) int64 10 2 3

Copy link
Contributor Author

Choose a reason for hiding this comment

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

group_id is removed from coords in this line

coords.discard(name)

If we comment this line and run our example again, group_id appears in coords after cumsum. I need some help to understand what this line does.

Copy link
Collaborator

Choose a reason for hiding this comment

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

I could look more.

Does anyone who have more experience with this code know what's happening?

},
coords={"x": [0, 1, 2, 3, 4, 5, 6]},
)

assert_identical(expected, actual)


# TODO: move other groupby tests from test_dataset and test_dataarray over here