-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
groupby.py
1882 lines (1592 loc) · 64 KB
/
groupby.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import datetime
import warnings
from abc import ABC, abstractmethod
from collections.abc import Hashable, Iterator, Mapping, Sequence
from dataclasses import dataclass, field
from typing import (
TYPE_CHECKING,
Any,
Callable,
Generic,
Literal,
Union,
)
import numpy as np
import pandas as pd
from xarray.core import dtypes, duck_array_ops, nputils, ops
from xarray.core._aggregations import (
DataArrayGroupByAggregations,
DatasetGroupByAggregations,
)
from xarray.core.alignment import align
from xarray.core.arithmetic import DataArrayGroupbyArithmetic, DatasetGroupbyArithmetic
from xarray.core.common import ImplementsArrayReduce, ImplementsDatasetReduce
from xarray.core.concat import concat
from xarray.core.formatting import format_array_flat
from xarray.core.indexes import (
create_default_index_implicit,
filter_indexes_from_coords,
safe_cast_to_index,
)
from xarray.core.options import _get_keep_attrs
from xarray.core.types import Dims, QuantileMethods, T_DataArray, T_Xarray
from xarray.core.utils import (
FrozenMappingWarningOnValuesAccess,
either_dict_or_kwargs,
emit_user_level_warning,
hashable,
is_scalar,
maybe_wrap_array,
peek_at,
)
from xarray.core.variable import IndexVariable, Variable
from xarray.util.deprecation_helpers import _deprecate_positional_args
if TYPE_CHECKING:
from numpy.typing import ArrayLike
from xarray.core.dataarray import DataArray
from xarray.core.dataset import Dataset
from xarray.core.resample_cftime import CFTimeGrouper
from xarray.core.types import DatetimeLike, SideOptions
from xarray.core.utils import Frozen
GroupKey = Any
GroupIndex = Union[int, slice, list[int]]
T_GroupIndices = list[GroupIndex]
T_FactorizeOut = tuple[
DataArray, T_GroupIndices, Union[IndexVariable, "_DummyGroup"], pd.Index
]
def check_reduce_dims(reduce_dims, dimensions):
if reduce_dims is not ...:
if is_scalar(reduce_dims):
reduce_dims = [reduce_dims]
if any(dim not in dimensions for dim in reduce_dims):
raise ValueError(
f"cannot reduce over dimensions {reduce_dims!r}. expected either '...' "
f"to reduce over all dimensions or one or more of {dimensions!r}."
f" Try passing .groupby(..., squeeze=False)"
)
def _maybe_squeeze_indices(
indices, squeeze: bool | None, grouper: ResolvedGrouper, warn: bool
):
if squeeze in [None, True] and grouper.can_squeeze:
if isinstance(indices, slice):
if indices.stop - indices.start == 1:
if (squeeze is None and warn) or squeeze is True:
emit_user_level_warning(
"The `squeeze` kwarg to GroupBy is being removed."
"Pass .groupby(..., squeeze=False) to disable squeezing,"
" which is the new default, and to silence this warning."
)
indices = indices.start
return indices
def unique_value_groups(
ar, sort: bool = True
) -> tuple[np.ndarray | pd.Index, T_GroupIndices, np.ndarray]:
"""Group an array by its unique values.
Parameters
----------
ar : array-like
Input array. This will be flattened if it is not already 1-D.
sort : bool, default: True
Whether or not to sort unique values.
Returns
-------
values : np.ndarray
Sorted, unique values as returned by `np.unique`.
indices : list of lists of int
Each element provides the integer indices in `ar` with values given by
the corresponding value in `unique_values`.
"""
inverse, values = pd.factorize(ar, sort=sort)
if isinstance(values, pd.MultiIndex):
values.names = ar.names
groups = _codes_to_groups(inverse, len(values))
return values, groups, inverse
def _codes_to_groups(inverse: np.ndarray, N: int) -> T_GroupIndices:
groups: T_GroupIndices = [[] for _ in range(N)]
for n, g in enumerate(inverse):
if g >= 0:
groups[g].append(n)
return groups
def _dummy_copy(xarray_obj):
from xarray.core.dataarray import DataArray
from xarray.core.dataset import Dataset
if isinstance(xarray_obj, Dataset):
res = Dataset(
{
k: dtypes.get_fill_value(v.dtype)
for k, v in xarray_obj.data_vars.items()
},
{
k: dtypes.get_fill_value(v.dtype)
for k, v in xarray_obj.coords.items()
if k not in xarray_obj.dims
},
xarray_obj.attrs,
)
elif isinstance(xarray_obj, DataArray):
res = DataArray(
dtypes.get_fill_value(xarray_obj.dtype),
{
k: dtypes.get_fill_value(v.dtype)
for k, v in xarray_obj.coords.items()
if k not in xarray_obj.dims
},
dims=[],
name=xarray_obj.name,
attrs=xarray_obj.attrs,
)
else: # pragma: no cover
raise AssertionError
return res
def _is_one_or_none(obj) -> bool:
return obj == 1 or obj is None
def _consolidate_slices(slices: list[slice]) -> list[slice]:
"""Consolidate adjacent slices in a list of slices."""
result: list[slice] = []
last_slice = slice(None)
for slice_ in slices:
if not isinstance(slice_, slice):
raise ValueError(f"list element is not a slice: {slice_!r}")
if (
result
and last_slice.stop == slice_.start
and _is_one_or_none(last_slice.step)
and _is_one_or_none(slice_.step)
):
last_slice = slice(last_slice.start, slice_.stop, slice_.step)
result[-1] = last_slice
else:
result.append(slice_)
last_slice = slice_
return result
def _inverse_permutation_indices(positions, N: int | None = None) -> np.ndarray | None:
"""Like inverse_permutation, but also handles slices.
Parameters
----------
positions : list of ndarray or slice
If slice objects, all are assumed to be slices.
Returns
-------
np.ndarray of indices or None, if no permutation is necessary.
"""
if not positions:
return None
if isinstance(positions[0], slice):
positions = _consolidate_slices(positions)
if positions == slice(None):
return None
positions = [np.arange(sl.start, sl.stop, sl.step) for sl in positions]
newpositions = nputils.inverse_permutation(np.concatenate(positions), N)
return newpositions[newpositions != -1]
class _DummyGroup(Generic[T_Xarray]):
"""Class for keeping track of grouped dimensions without coordinates.
Should not be user visible.
"""
__slots__ = ("name", "coords", "size", "dataarray")
def __init__(self, obj: T_Xarray, name: Hashable, coords) -> None:
self.name = name
self.coords = coords
self.size = obj.sizes[name]
@property
def dims(self) -> tuple[Hashable]:
return (self.name,)
@property
def ndim(self) -> Literal[1]:
return 1
@property
def values(self) -> range:
return range(self.size)
@property
def data(self) -> range:
return range(self.size)
def __array__(self) -> np.ndarray:
return np.arange(self.size)
@property
def shape(self) -> tuple[int]:
return (self.size,)
@property
def attrs(self) -> dict:
return {}
def __getitem__(self, key):
if isinstance(key, tuple):
key = key[0]
return self.values[key]
def to_index(self) -> pd.Index:
# could be pd.RangeIndex?
return pd.Index(np.arange(self.size))
def copy(self, deep: bool = True, data: Any = None):
raise NotImplementedError
def to_dataarray(self) -> DataArray:
from xarray.core.dataarray import DataArray
return DataArray(
data=self.data, dims=(self.name,), coords=self.coords, name=self.name
)
def to_array(self) -> DataArray:
"""Deprecated version of to_dataarray."""
return self.to_dataarray()
T_Group = Union["T_DataArray", "IndexVariable", _DummyGroup]
def _ensure_1d(
group: T_Group, obj: T_Xarray
) -> tuple[T_Group, T_Xarray, Hashable | None, list[Hashable],]:
# 1D cases: do nothing
if isinstance(group, (IndexVariable, _DummyGroup)) or group.ndim == 1:
return group, obj, None, []
from xarray.core.dataarray import DataArray
if isinstance(group, DataArray):
# try to stack the dims of the group into a single dim
orig_dims = group.dims
stacked_dim = "stacked_" + "_".join(map(str, orig_dims))
# these dimensions get created by the stack operation
inserted_dims = [dim for dim in group.dims if dim not in group.coords]
newgroup = group.stack({stacked_dim: orig_dims})
newobj = obj.stack({stacked_dim: orig_dims})
return newgroup, newobj, stacked_dim, inserted_dims
raise TypeError(
f"group must be DataArray, IndexVariable or _DummyGroup, got {type(group)!r}."
)
def _apply_loffset(
loffset: str | pd.DateOffset | datetime.timedelta | pd.Timedelta,
result: pd.Series | pd.DataFrame,
):
"""
(copied from pandas)
if loffset is set, offset the result index
This is NOT an idempotent routine, it will be applied
exactly once to the result.
Parameters
----------
result : Series or DataFrame
the result of resample
"""
# pd.Timedelta is a subclass of datetime.timedelta so we do not need to
# include it in instance checks.
if not isinstance(loffset, (str, pd.DateOffset, datetime.timedelta)):
raise ValueError(
f"`loffset` must be a str, pd.DateOffset, datetime.timedelta, or pandas.Timedelta object. "
f"Got {loffset}."
)
if isinstance(loffset, str):
loffset = pd.tseries.frequencies.to_offset(loffset)
needs_offset = (
isinstance(loffset, (pd.DateOffset, datetime.timedelta))
and isinstance(result.index, pd.DatetimeIndex)
and len(result.index) > 0
)
if needs_offset:
result.index = result.index + loffset
@dataclass
class ResolvedGrouper(ABC, Generic[T_Xarray]):
grouper: Grouper
group: T_Group
obj: T_Xarray
_group_as_index: pd.Index | None = field(default=None, init=False)
# Defined by factorize:
codes: DataArray = field(init=False)
group_indices: T_GroupIndices = field(init=False)
unique_coord: IndexVariable | _DummyGroup = field(init=False)
full_index: pd.Index = field(init=False)
# _ensure_1d:
group1d: T_Group = field(init=False)
stacked_obj: T_Xarray = field(init=False)
stacked_dim: Hashable | None = field(init=False)
inserted_dims: list[Hashable] = field(init=False)
def __post_init__(self) -> None:
self.group: T_Group = _resolve_group(self.obj, self.group)
(
self.group1d,
self.stacked_obj,
self.stacked_dim,
self.inserted_dims,
) = _ensure_1d(group=self.group, obj=self.obj)
@property
def name(self) -> Hashable:
return self.group1d.name
@property
def size(self) -> int:
return len(self)
def __len__(self) -> int:
return len(self.full_index) # TODO: full_index not def, abstractmethod?
@property
def dims(self):
return self.group1d.dims
@abstractmethod
def factorize(self) -> T_FactorizeOut:
raise NotImplementedError
def _factorize(self) -> None:
# This design makes it clear to mypy that
# codes, group_indices, unique_coord, and full_index
# are set by the factorize method on the derived class.
(
self.codes,
self.group_indices,
self.unique_coord,
self.full_index,
) = self.factorize()
@property
def is_unique_and_monotonic(self) -> bool:
if isinstance(self.group, _DummyGroup):
return True
index = self.group_as_index
return index.is_unique and index.is_monotonic_increasing
@property
def group_as_index(self) -> pd.Index:
if self._group_as_index is None:
self._group_as_index = self.group1d.to_index()
return self._group_as_index
@property
def can_squeeze(self) -> bool:
is_resampler = isinstance(self.grouper, TimeResampleGrouper)
is_dimension = self.group.dims == (self.group.name,)
return not is_resampler and is_dimension and self.is_unique_and_monotonic
@dataclass
class ResolvedUniqueGrouper(ResolvedGrouper):
grouper: UniqueGrouper
def factorize(self) -> T_FactorizeOut:
if self.can_squeeze:
return self._factorize_dummy()
else:
return self._factorize_unique()
def _factorize_unique(self) -> T_FactorizeOut:
# look through group to find the unique values
sort = not isinstance(self.group_as_index, pd.MultiIndex)
unique_values, group_indices, codes_ = unique_value_groups(
self.group_as_index, sort=sort
)
if len(group_indices) == 0:
raise ValueError(
"Failed to group data. Are you grouping by a variable that is all NaN?"
)
codes = self.group1d.copy(data=codes_)
group_indices = group_indices
unique_coord = IndexVariable(
self.group.name, unique_values, attrs=self.group.attrs
)
full_index = unique_coord
return codes, group_indices, unique_coord, full_index
def _factorize_dummy(self) -> T_FactorizeOut:
size = self.group.size
# no need to factorize
# use slices to do views instead of fancy indexing
# equivalent to: group_indices = group_indices.reshape(-1, 1)
group_indices: T_GroupIndices = [slice(i, i + 1) for i in range(size)]
size_range = np.arange(size)
if isinstance(self.group, _DummyGroup):
codes = self.group.to_dataarray().copy(data=size_range)
else:
codes = self.group.copy(data=size_range)
unique_coord = self.group
full_index = IndexVariable(self.name, unique_coord.values, self.group.attrs)
return codes, group_indices, unique_coord, full_index
@dataclass
class ResolvedBinGrouper(ResolvedGrouper):
grouper: BinGrouper
def factorize(self) -> T_FactorizeOut:
from xarray.core.dataarray import DataArray
data = self.group1d.values
binned, bins = pd.cut(
data, self.grouper.bins, **self.grouper.cut_kwargs, retbins=True
)
binned_codes = binned.codes
if (binned_codes == -1).all():
raise ValueError(f"None of the data falls within bins with edges {bins!r}")
full_index = binned.categories
uniques = np.sort(pd.unique(binned_codes))
unique_values = full_index[uniques[uniques != -1]]
group_indices = [
g for g in _codes_to_groups(binned_codes, len(full_index)) if g
]
if len(group_indices) == 0:
raise ValueError(f"None of the data falls within bins with edges {bins!r}")
new_dim_name = str(self.group.name) + "_bins"
self.group1d = DataArray(
binned, getattr(self.group1d, "coords", None), name=new_dim_name
)
unique_coord = IndexVariable(new_dim_name, unique_values, self.group.attrs)
codes = self.group1d.copy(data=binned_codes)
# TODO: support IntervalIndex in IndexVariable
return codes, group_indices, unique_coord, full_index
@dataclass
class ResolvedTimeResampleGrouper(ResolvedGrouper):
grouper: TimeResampleGrouper
index_grouper: CFTimeGrouper | pd.Grouper = field(init=False)
def __post_init__(self) -> None:
super().__post_init__()
from xarray import CFTimeIndex
group_as_index = safe_cast_to_index(self.group)
self._group_as_index = group_as_index
if not group_as_index.is_monotonic_increasing:
# TODO: sort instead of raising an error
raise ValueError("index must be monotonic for resampling")
grouper = self.grouper
if isinstance(group_as_index, CFTimeIndex):
from xarray.core.resample_cftime import CFTimeGrouper
index_grouper = CFTimeGrouper(
freq=grouper.freq,
closed=grouper.closed,
label=grouper.label,
origin=grouper.origin,
offset=grouper.offset,
loffset=grouper.loffset,
)
else:
index_grouper = pd.Grouper(
freq=grouper.freq,
closed=grouper.closed,
label=grouper.label,
origin=grouper.origin,
offset=grouper.offset,
)
self.index_grouper = index_grouper
def _get_index_and_items(self) -> tuple[pd.Index, pd.Series, np.ndarray]:
first_items, codes = self.first_items()
full_index = first_items.index
if first_items.isnull().any():
first_items = first_items.dropna()
full_index = full_index.rename("__resample_dim__")
return full_index, first_items, codes
def first_items(self) -> tuple[pd.Series, np.ndarray]:
from xarray import CFTimeIndex
if isinstance(self.group_as_index, CFTimeIndex):
return self.index_grouper.first_items(self.group_as_index)
else:
s = pd.Series(np.arange(self.group_as_index.size), self.group_as_index)
grouped = s.groupby(self.index_grouper)
first_items = grouped.first()
counts = grouped.count()
# This way we generate codes for the final output index: full_index.
# So for _flox_reduce we avoid one reindex and copy by avoiding
# _maybe_restore_empty_groups
codes = np.repeat(np.arange(len(first_items)), counts)
if self.grouper.loffset is not None:
_apply_loffset(self.grouper.loffset, first_items)
return first_items, codes
def factorize(self) -> T_FactorizeOut:
full_index, first_items, codes_ = self._get_index_and_items()
sbins = first_items.values.astype(np.int64)
group_indices: T_GroupIndices = [
slice(i, j) for i, j in zip(sbins[:-1], sbins[1:])
]
group_indices += [slice(sbins[-1], None)]
unique_coord = IndexVariable(
self.group.name, first_items.index, self.group.attrs
)
codes = self.group.copy(data=codes_)
return codes, group_indices, unique_coord, full_index
class Grouper(ABC):
pass
@dataclass
class UniqueGrouper(Grouper):
pass
@dataclass
class BinGrouper(Grouper):
bins: Any # TODO: What is the typing?
cut_kwargs: Mapping = field(default_factory=dict)
def __post_init__(self) -> None:
if duck_array_ops.isnull(self.bins).all():
raise ValueError("All bin edges are NaN.")
@dataclass
class TimeResampleGrouper(Grouper):
freq: str
closed: SideOptions | None
label: SideOptions | None
origin: str | DatetimeLike | None
offset: pd.Timedelta | datetime.timedelta | str | None
loffset: datetime.timedelta | str | None
def _validate_groupby_squeeze(squeeze: bool | None) -> None:
# While we don't generally check the type of every arg, passing
# multiple dimensions as multiple arguments is common enough, and the
# consequences hidden enough (strings evaluate as true) to warrant
# checking here.
# A future version could make squeeze kwarg only, but would face
# backward-compat issues.
if squeeze is not None and not isinstance(squeeze, bool):
raise TypeError(
f"`squeeze` must be None, True or False, but {squeeze} was supplied"
)
def _resolve_group(obj: T_Xarray, group: T_Group | Hashable) -> T_Group:
from xarray.core.dataarray import DataArray
error_msg = (
"the group variable's length does not "
"match the length of this variable along its "
"dimensions"
)
newgroup: T_Group
if isinstance(group, DataArray):
try:
align(obj, group, join="exact", copy=False)
except ValueError:
raise ValueError(error_msg)
newgroup = group.copy(deep=False)
newgroup.name = group.name or "group"
elif isinstance(group, IndexVariable):
# This assumption is built in to _ensure_1d.
if group.ndim != 1:
raise ValueError(
"Grouping by multi-dimensional IndexVariables is not allowed."
"Convert to and pass a DataArray instead."
)
(group_dim,) = group.dims
if len(group) != obj.sizes[group_dim]:
raise ValueError(error_msg)
newgroup = DataArray(group)
else:
if not hashable(group):
raise TypeError(
"`group` must be an xarray.DataArray or the "
"name of an xarray variable or dimension. "
f"Received {group!r} instead."
)
group = obj[group]
if group.name not in obj._indexes and group.name in obj.dims:
# DummyGroups should not appear on groupby results
newgroup = _DummyGroup(obj, group.name, group.coords)
else:
newgroup = group
if newgroup.size == 0:
raise ValueError(f"{newgroup.name} must not be empty")
return newgroup
class GroupBy(Generic[T_Xarray]):
"""A object that implements the split-apply-combine pattern.
Modeled after `pandas.GroupBy`. The `GroupBy` object can be iterated over
(unique_value, grouped_array) pairs, but the main way to interact with a
groupby object are with the `apply` or `reduce` methods. You can also
directly call numpy methods like `mean` or `std`.
You should create a GroupBy object by using the `DataArray.groupby` or
`Dataset.groupby` methods.
See Also
--------
Dataset.groupby
DataArray.groupby
"""
__slots__ = (
"_full_index",
"_inserted_dims",
"_group",
"_group_dim",
"_group_indices",
"_groups",
"groupers",
"_obj",
"_restore_coord_dims",
"_stacked_dim",
"_unique_coord",
"_dims",
"_sizes",
"_squeeze",
# Save unstacked object for flox
"_original_obj",
"_original_group",
"_bins",
"_codes",
)
_obj: T_Xarray
groupers: tuple[ResolvedGrouper]
_squeeze: bool | None
_restore_coord_dims: bool
_original_obj: T_Xarray
_original_group: T_Group
_group_indices: T_GroupIndices
_codes: DataArray
_group_dim: Hashable
_groups: dict[GroupKey, GroupIndex] | None
_dims: tuple[Hashable, ...] | Frozen[Hashable, int] | None
_sizes: Mapping[Hashable, int] | None
def __init__(
self,
obj: T_Xarray,
groupers: tuple[ResolvedGrouper],
squeeze: bool | None = False,
restore_coord_dims: bool = True,
) -> None:
"""Create a GroupBy object
Parameters
----------
obj : Dataset or DataArray
Object to group.
grouper : Grouper
Grouper object
restore_coord_dims : bool, default: True
If True, also restore the dimension order of multi-dimensional
coordinates.
"""
self.groupers = groupers
self._original_obj = obj
for grouper_ in self.groupers:
grouper_._factorize()
(grouper,) = self.groupers
self._original_group = grouper.group
# specification for the groupby operation
self._obj = grouper.stacked_obj
self._restore_coord_dims = restore_coord_dims
self._squeeze = squeeze
# These should generalize to multiple groupers
self._group_indices = grouper.group_indices
self._codes = self._maybe_unstack(grouper.codes)
(self._group_dim,) = grouper.group1d.dims
# cached attributes
self._groups = None
self._dims = None
self._sizes = None
@property
def sizes(self) -> Mapping[Hashable, int]:
"""Ordered mapping from dimension names to lengths.
Immutable.
See Also
--------
DataArray.sizes
Dataset.sizes
"""
if self._sizes is None:
(grouper,) = self.groupers
index = _maybe_squeeze_indices(
self._group_indices[0],
self._squeeze,
grouper,
warn=True,
)
self._sizes = self._obj.isel({self._group_dim: index}).sizes
return self._sizes
def map(
self,
func: Callable,
args: tuple[Any, ...] = (),
shortcut: bool | None = None,
**kwargs: Any,
) -> T_Xarray:
raise NotImplementedError()
def reduce(
self,
func: Callable[..., Any],
dim: Dims = None,
*,
axis: int | Sequence[int] | None = None,
keep_attrs: bool | None = None,
keepdims: bool = False,
shortcut: bool = True,
**kwargs: Any,
) -> T_Xarray:
raise NotImplementedError()
@property
def groups(self) -> dict[GroupKey, GroupIndex]:
"""
Mapping from group labels to indices. The indices can be used to index the underlying object.
"""
# provided to mimic pandas.groupby
if self._groups is None:
(grouper,) = self.groupers
squeezed_indices = (
_maybe_squeeze_indices(ind, self._squeeze, grouper, warn=idx > 0)
for idx, ind in enumerate(self._group_indices)
)
self._groups = dict(zip(grouper.unique_coord.values, squeezed_indices))
return self._groups
def __getitem__(self, key: GroupKey) -> T_Xarray:
"""
Get DataArray or Dataset corresponding to a particular group label.
"""
(grouper,) = self.groupers
index = _maybe_squeeze_indices(
self.groups[key], self._squeeze, grouper, warn=True
)
return self._obj.isel({self._group_dim: index})
def __len__(self) -> int:
(grouper,) = self.groupers
return grouper.size
def __iter__(self) -> Iterator[tuple[GroupKey, T_Xarray]]:
(grouper,) = self.groupers
return zip(grouper.unique_coord.data, self._iter_grouped())
def __repr__(self) -> str:
(grouper,) = self.groupers
return "{}, grouped over {!r}\n{!r} groups with labels {}.".format(
self.__class__.__name__,
grouper.name,
grouper.full_index.size,
", ".join(format_array_flat(grouper.full_index, 30).split()),
)
def _iter_grouped(self, warn_squeeze=True) -> Iterator[T_Xarray]:
"""Iterate over each element in this group"""
(grouper,) = self.groupers
for idx, indices in enumerate(self._group_indices):
indices = _maybe_squeeze_indices(
indices, self._squeeze, grouper, warn=warn_squeeze and idx == 0
)
yield self._obj.isel({self._group_dim: indices})
def _infer_concat_args(self, applied_example):
(grouper,) = self.groupers
if self._group_dim in applied_example.dims:
coord = grouper.group1d
positions = self._group_indices
else:
coord = grouper.unique_coord
positions = None
(dim,) = coord.dims
if isinstance(coord, _DummyGroup):
coord = None
coord = getattr(coord, "variable", coord)
return coord, dim, positions
def _binary_op(self, other, f, reflexive=False):
from xarray.core.dataarray import DataArray
from xarray.core.dataset import Dataset
g = f if not reflexive else lambda x, y: f(y, x)
(grouper,) = self.groupers
obj = self._original_obj
group = grouper.group
codes = self._codes
dims = group.dims
if isinstance(group, _DummyGroup):
group = coord = group.to_dataarray()
else:
coord = grouper.unique_coord
if not isinstance(coord, DataArray):
coord = DataArray(grouper.unique_coord)
name = grouper.name
if not isinstance(other, (Dataset, DataArray)):
raise TypeError(
"GroupBy objects only support binary ops "
"when the other argument is a Dataset or "
"DataArray"
)
if name not in other.dims:
raise ValueError(
"incompatible dimensions for a grouped "
f"binary operation: the group variable {name!r} "
"is not a dimension on the other argument "
f"with dimensions {other.dims!r}"
)
# Broadcast out scalars for backwards compatibility
# TODO: get rid of this when fixing GH2145
for var in other.coords:
if other[var].ndim == 0:
other[var] = (
other[var].drop_vars(var).expand_dims({name: other.sizes[name]})
)
# need to handle NaNs in group or elements that don't belong to any bins
mask = codes == -1
if mask.any():
obj = obj.where(~mask, drop=True)
group = group.where(~mask, drop=True)
codes = codes.where(~mask, drop=True).astype(int)
# if other is dask-backed, that's a hint that the
# "expanded" dataset is too big to hold in memory.
# this can be the case when `other` was read from disk
# and contains our lazy indexing classes
# We need to check for dask-backed Datasets
# so utils.is_duck_dask_array does not work for this check
if obj.chunks and not other.chunks:
# TODO: What about datasets with some dask vars, and others not?
# This handles dims other than `name``
chunks = {k: v for k, v in obj.chunksizes.items() if k in other.dims}
# a chunk size of 1 seems reasonable since we expect individual elements of
# other to be repeated multiple times across the reduced dimension(s)
chunks[name] = 1
other = other.chunk(chunks)
# codes are defined for coord, so we align `other` with `coord`
# before indexing
other, _ = align(other, coord, join="right", copy=False)
expanded = other.isel({name: codes})
result = g(obj, expanded)
if group.ndim > 1:
# backcompat:
# TODO: get rid of this when fixing GH2145
for var in set(obj.coords) - set(obj.xindexes):
if set(obj[var].dims) < set(group.dims):
result[var] = obj[var].reset_coords(drop=True).broadcast_like(group)
if isinstance(result, Dataset) and isinstance(obj, Dataset):
for var in set(result):
for d in dims:
if d not in obj[var].dims:
result[var] = result[var].transpose(d, ...)
return result
def _maybe_restore_empty_groups(self, combined):
"""Our index contained empty groups (e.g., from a resampling or binning). If we
reduced on that dimension, we want to restore the full index.
"""
(grouper,) = self.groupers
if (
isinstance(grouper, (ResolvedBinGrouper, ResolvedTimeResampleGrouper))
and grouper.name in combined.dims
):
indexers = {grouper.name: grouper.full_index}
combined = combined.reindex(**indexers)
return combined
def _maybe_unstack(self, obj):
"""This gets called if we are applying on an array with a
multidimensional group."""
(grouper,) = self.groupers
stacked_dim = grouper.stacked_dim
inserted_dims = grouper.inserted_dims
if stacked_dim is not None and stacked_dim in obj.dims:
obj = obj.unstack(stacked_dim)
for dim in inserted_dims:
if dim in obj.coords:
del obj.coords[dim]
obj._indexes = filter_indexes_from_coords(obj._indexes, set(obj.coords))
return obj
def _flox_reduce(
self,