Skip to content

Commit 36a9b01

Browse files
authored
Support GroupBy iteration and arithmetic (#158)
Fixes #157
1 parent d73d9f5 commit 36a9b01

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

cf_xarray/accessor.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
import xarray as xr
2121
from xarray import DataArray, Dataset
22+
from xarray.core.arithmetic import SupportsArithmetic
2223

2324
from .helpers import bounds_to_vertices
2425
from .utils import _is_datetime_like, invert_mappings, parse_cell_methods_attr
@@ -693,7 +694,7 @@ def _get_possible(accessor, criteria):
693694
return _get_possible(obj.cf, y_criteria)
694695

695696

696-
class _CFWrappedClass:
697+
class _CFWrappedClass(SupportsArithmetic):
697698
"""
698699
This class is used to wrap any class in _WRAPPED_CLASSES.
699700
"""
@@ -721,6 +722,9 @@ def __getattr__(self, attr):
721722
key_mappers=_DEFAULT_KEY_MAPPERS,
722723
)
723724

725+
def __iter__(self):
726+
return iter(self.wrapped)
727+
724728

725729
class _CFWrappedPlotMethods:
726730
"""

cf_xarray/tests/test_accessor.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -786,3 +786,18 @@ def makeds(*dims):
786786
xtds = makeds("X", "T")
787787
assert _possible_x_y_plot(xtds, "y") is None
788788
assert _possible_x_y_plot(xtds, "x") == "X"
789+
790+
791+
def test_groupby_special_ops():
792+
cfgrouped = airds.cf.groupby_bins("latitude", np.arange(20, 50, 10))
793+
grouped = airds.groupby_bins("lat", np.arange(20, 50, 10))
794+
795+
# __iter__
796+
for (label, group), (cflabel, cfgroup) in zip(grouped, cfgrouped):
797+
assert label == cflabel
798+
assert_identical(group, cfgroup)
799+
800+
# arithmetic
801+
expected = grouped - grouped.mean()
802+
actual = grouped - cfgrouped.mean()
803+
assert_identical(expected, actual)

doc/whats-new.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ v0.4.1 (unreleased)
1515
by :py:meth:`Dataset.cf.__getitem__`. This allows extraction of DataArrays when there are clashes
1616
between DataArray names and "special" CF names like ``T``.
1717
(:issue:`129`, :pr:`130`). By `Deepak Cherian`_
18+
- Fix iteration and arithemtic with ``GroupBy`` objects. By `Deepak Cherian`_.
1819

1920
v0.4.0 (Jan 22, 2021)
2021
=====================

0 commit comments

Comments
 (0)