From 73b013f22fe050ecd758b9c13fb5a06c4a8ba22e Mon Sep 17 00:00:00 2001 From: Phillip Butcher Date: Sat, 30 May 2020 06:15:55 -0700 Subject: [PATCH] Assign default group name in groupby if name=None (#158) (#4098) * Assign default group name in groupby (#158) * When groupby receives a DataArray with name=None assign name='group' * Previously when name=None a ValueError: `group` must have a name was raised * Closes #158 * Add test * Update whats-new.rst * black * Add assert statement to test group name was added to DataArray Co-authored-by: phillipbutcher --- doc/whats-new.rst | 2 ++ xarray/core/groupby.py | 2 +- xarray/tests/test_groupby.py | 12 ++++++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/doc/whats-new.rst b/doc/whats-new.rst index a32e0393bcf..e06ed5be897 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -100,6 +100,8 @@ New Features Bug fixes ~~~~~~~~~ +- If groupby receives a ``DataArray`` with name=None, assign a default name (:issue:`158`) + By `Phil Butcher `_. - Support dark mode in VS code (:issue:`4024`) By `Keisuke Fujii `_. - Fix bug when converting multiindexed Pandas objects to sparse xarray objects. (:issue:`4019`) diff --git a/xarray/core/groupby.py b/xarray/core/groupby.py index 299cb8ec4fa..04c0fabae6a 100644 --- a/xarray/core/groupby.py +++ b/xarray/core/groupby.py @@ -321,7 +321,7 @@ def __init__( group = _DummyGroup(obj, group.name, group.coords) if getattr(group, "name", None) is None: - raise ValueError("`group` must have a name") + group.name = "group" group, obj, stacked_dim, inserted_dims = _ensure_1d(group, obj) (group_dim,) = group.dims diff --git a/xarray/tests/test_groupby.py b/xarray/tests/test_groupby.py index 866d5fb0899..aa54c8f36f1 100644 --- a/xarray/tests/test_groupby.py +++ b/xarray/tests/test_groupby.py @@ -538,4 +538,16 @@ def test_groupby_bins_timeseries(): assert_identical(actual, expected) +def test_groupby_none_group_name(): + # GH158 + # xarray should not fail if a DataArray's name attribute is None + + data = np.arange(10) + 10 + da = xr.DataArray(data) # da.name = None + key = xr.DataArray(np.floor_divide(data, 2)) + + mean = da.groupby(key).mean() + assert "group" in mean.dims + + # TODO: move other groupby tests from test_dataset and test_dataarray over here