Skip to content

FlagGrouper: Encapsulate instead of subclassing UniqueGrouper #569

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

Merged
merged 1 commit into from
Apr 15, 2025
Merged
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
15 changes: 11 additions & 4 deletions cf_xarray/groupers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@

import numpy as np
import pandas as pd
from xarray.groupers import EncodedGroups, UniqueGrouper
from xarray import Variable
from xarray.groupers import EncodedGroups, Grouper, UniqueGrouper


@dataclass
class FlagGrouper(UniqueGrouper):
class FlagGrouper(Grouper):
"""
Grouper object that allows convenient categorical grouping by a CF flag variable.

Expand All @@ -23,18 +24,24 @@ def factorize(self, group) -> EncodedGroups:
values = np.array(group.attrs["flag_values"])
full_index = pd.Index(group.attrs["flag_meanings"].split(" "))

self.labels = values
grouper = UniqueGrouper(labels=values)

# TODO: we could optimize here, since `group` is already factorized,
# but there are subtleties. For example, the attrs must be up to date,
# any value that is not in flag_values will cause an error, etc.
ret = super().factorize(group)
ret = grouper.factorize(group)

ret.codes.attrs.pop("flag_values")
ret.codes.attrs.pop("flag_meanings")

return EncodedGroups(
codes=ret.codes,
full_index=full_index,
unique_coord=Variable(
dims=ret.codes.name, data=np.array(full_index), attrs=ret.codes.attrs
),
group_indices=ret.group_indices,
)

def reset(self):
raise NotImplementedError()
Loading