This repository was archived by the owner on Apr 1, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathseries_group_by.py
More file actions
422 lines (370 loc) · 14.1 KB
/
series_group_by.py
File metadata and controls
422 lines (370 loc) · 14.1 KB
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
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import datetime
import typing
from typing import Literal, Sequence, Union
import bigframes_vendored.constants as constants
import bigframes_vendored.pandas.core.groupby as vendored_pandas_groupby
import numpy
import pandas
from bigframes import session
from bigframes.core import expression as ex
from bigframes.core import log_adapter
import bigframes.core.block_transforms as block_ops
import bigframes.core.blocks as blocks
from bigframes.core.groupby import aggs
import bigframes.core.ordering as order
import bigframes.core.utils as utils
import bigframes.core.validations as validations
from bigframes.core.window import rolling
import bigframes.core.window as windows
import bigframes.core.window_spec as window_specs
import bigframes.dataframe as df
import bigframes.dtypes
import bigframes.operations.aggregations as agg_ops
import bigframes.series as series
@log_adapter.class_logger
class SeriesGroupBy(vendored_pandas_groupby.SeriesGroupBy):
__doc__ = vendored_pandas_groupby.GroupBy.__doc__
def __init__(
self,
block: blocks.Block,
value_column: str,
by_col_ids: typing.Sequence[str],
value_name: blocks.Label = None,
dropna=True,
):
# TODO(tbergeron): Support more group-by expression types
self._block = block
self._value_column = value_column
self._by_col_ids = by_col_ids
self._value_name = value_name
self._dropna = dropna # Applies to aggregations but not windowing
@property
def _session(self) -> session.Session:
return self._block.session
@validations.requires_ordering()
def head(self, n: int = 5) -> series.Series:
block = self._block
if self._dropna:
block = block_ops.dropna(self._block, self._by_col_ids, how="any")
return series.Series(
block.grouped_head(
by_column_ids=self._by_col_ids, value_columns=[self._value_column], n=n
)
)
def describe(self, include: None | Literal["all"] = None):
from bigframes.pandas.core.methods import describe
return df.DataFrame(
describe._describe(
self._block,
columns=[self._value_column],
include=include,
as_index=True,
by_col_ids=self._by_col_ids,
dropna=self._dropna,
)
).droplevel(level=0, axis=1)
def all(self) -> series.Series:
return self._aggregate(agg_ops.all_op)
def any(self) -> series.Series:
return self._aggregate(agg_ops.any_op)
def min(self, *args) -> series.Series:
return self._aggregate(agg_ops.min_op)
def max(self, *args) -> series.Series:
return self._aggregate(agg_ops.max_op)
def count(self) -> series.Series:
return self._aggregate(agg_ops.count_op)
def nunique(self) -> series.Series:
return self._aggregate(agg_ops.nunique_op)
def sum(self, *args) -> series.Series:
return self._aggregate(agg_ops.sum_op)
def mean(self, *args) -> series.Series:
return self._aggregate(agg_ops.mean_op)
def rank(
self,
method="average",
ascending: bool = True,
na_option: str = "keep",
pct: bool = False,
) -> series.Series:
return series.Series(
block_ops.rank(
self._block,
method,
na_option,
ascending,
grouping_cols=tuple(self._by_col_ids),
columns=(self._value_column,),
pct=pct,
)
)
def median(
self,
*args,
exact: bool = True,
**kwargs,
) -> series.Series:
if exact:
return self.quantile(0.5)
else:
return self._aggregate(agg_ops.median_op)
def quantile(
self, q: Union[float, Sequence[float]] = 0.5, *, numeric_only: bool = False
) -> series.Series:
multi_q = utils.is_list_like(q)
result = block_ops.quantile(
self._block,
(self._value_column,),
qs=tuple(q) if multi_q else (q,), # type: ignore
grouping_column_ids=self._by_col_ids,
dropna=self._dropna,
)
if multi_q:
return series.Series(result.stack())
else:
return series.Series(result.stack()).droplevel(-1)
def std(self, *args, **kwargs) -> series.Series:
return self._aggregate(agg_ops.std_op)
def var(self, *args, **kwargs) -> series.Series:
return self._aggregate(agg_ops.var_op)
def size(self) -> series.Series:
agg_block, _ = self._block.aggregate_size(
by_column_ids=self._by_col_ids,
dropna=self._dropna,
)
return series.Series(agg_block.with_column_labels([self._value_name]))
def skew(self, *args, **kwargs) -> series.Series:
block = block_ops.skew(self._block, [self._value_column], self._by_col_ids)
return series.Series(block)
def kurt(self, *args, **kwargs) -> series.Series:
block = block_ops.kurt(self._block, [self._value_column], self._by_col_ids)
return series.Series(block)
kurtosis = kurt
@validations.requires_ordering()
def first(self, numeric_only: bool = False, min_count: int = -1) -> series.Series:
if numeric_only and not bigframes.dtypes.is_numeric(
self._block.expr.get_column_type(self._value_column)
):
raise TypeError(
f"Cannot use 'numeric_only' with non-numeric column {self._value_name}."
)
window_spec = window_specs.unbound(
grouping_keys=tuple(self._by_col_ids),
min_periods=min_count if min_count >= 0 else 0,
)
block, firsts_id = self._block.apply_window_op(
self._value_column,
agg_ops.FirstNonNullOp(),
window_spec=window_spec,
)
block, _ = block.aggregate(
self._by_col_ids,
(aggs.agg(firsts_id, agg_ops.AnyValueOp()),),
dropna=self._dropna,
)
return series.Series(block.with_column_labels([self._value_name]))
@validations.requires_ordering()
def last(self, numeric_only: bool = False, min_count: int = -1) -> series.Series:
if numeric_only and not bigframes.dtypes.is_numeric(
self._block.expr.get_column_type(self._value_column)
):
raise TypeError(
f"Cannot use 'numeric_only' with non-numeric column {self._value_name}."
)
window_spec = window_specs.unbound(
grouping_keys=tuple(self._by_col_ids),
min_periods=min_count if min_count >= 0 else 0,
)
block, firsts_id = self._block.apply_window_op(
self._value_column,
agg_ops.LastNonNullOp(),
window_spec=window_spec,
)
block, _ = block.aggregate(
self._by_col_ids,
(aggs.agg(firsts_id, agg_ops.AnyValueOp()),),
dropna=self._dropna,
)
return series.Series(block.with_column_labels([self._value_name]))
def prod(self, *args) -> series.Series:
return self._aggregate(agg_ops.product_op)
def agg(self, func=None) -> typing.Union[df.DataFrame, series.Series]:
column_names: list[str] = []
if utils.is_dict_like(func):
raise NotImplementedError(
f"Aggregate with {func} not supported. {constants.FEEDBACK_LINK}"
)
if not utils.is_list_like(func):
func = [func]
aggregations = [
aggs.agg(self._value_column, agg_ops.lookup_agg_func(f)[0]) for f in func
]
column_names = [agg_ops.lookup_agg_func(f)[1] for f in func]
agg_block, _ = self._block.aggregate(
by_column_ids=self._by_col_ids,
aggregations=aggregations,
dropna=self._dropna,
)
if column_names:
agg_block = agg_block.with_column_labels(column_names)
if len(aggregations) > 1:
return df.DataFrame(agg_block)
return series.Series(agg_block)
aggregate = agg
def value_counts(
self,
normalize: bool = False,
sort: bool = True,
ascending: bool = False,
dropna: bool = True,
) -> Union[df.DataFrame, series.Series]:
columns = [self._value_column]
block = self._block
if self._dropna: # this drops null grouping columns
block = block_ops.dropna(block, self._by_col_ids)
block = block_ops.value_counts(
block,
columns,
normalize=normalize,
sort=sort,
ascending=ascending,
drop_na=dropna, # this drops null value columns
grouping_keys=self._by_col_ids,
)
# TODO: once as_index=Fales supported, return DataFrame instead by resetting index
# with .to_frame().reset_index(drop=False)
return series.Series(block)
@validations.requires_ordering()
def cumsum(self, *args, **kwargs) -> series.Series:
return self._apply_window_op(
agg_ops.sum_op,
)
@validations.requires_ordering()
def cumprod(self, *args, **kwargs) -> series.Series:
return self._apply_window_op(
agg_ops.product_op,
)
@validations.requires_ordering()
def cummax(self, *args, **kwargs) -> series.Series:
return self._apply_window_op(
agg_ops.max_op,
)
@validations.requires_ordering()
def cummin(self, *args, **kwargs) -> series.Series:
return self._apply_window_op(
agg_ops.min_op,
)
@validations.requires_ordering()
def cumcount(self, *args, **kwargs) -> series.Series:
# TODO: Add nullary op support to implement more cleanly
return (
self._apply_window_op(
agg_ops.SizeUnaryOp(),
discard_name=True,
never_skip_nulls=True,
)
- 1
)
@validations.requires_ordering()
def shift(self, periods=1) -> series.Series:
"""Shift index by desired number of periods."""
# Window framing clause is not allowed for analytic function lag.
window = window_specs.rows(
grouping_keys=tuple(self._by_col_ids),
)
return self._apply_window_op(agg_ops.ShiftOp(periods), window=window)
@validations.requires_ordering()
def diff(self, periods=1) -> series.Series:
window = window_specs.rows(
grouping_keys=tuple(self._by_col_ids),
)
return self._apply_window_op(agg_ops.DiffOp(periods), window=window)
@validations.requires_ordering()
def rolling(
self,
window: int | pandas.Timedelta | numpy.timedelta64 | datetime.timedelta | str,
min_periods=None,
closed: Literal["right", "left", "both", "neither"] = "right",
) -> windows.Window:
if isinstance(window, int):
window_spec = window_specs.WindowSpec(
bounds=window_specs.RowsWindowBounds.from_window_size(window, closed),
min_periods=min_periods if min_periods is not None else window,
grouping_keys=tuple(ex.deref(col) for col in self._by_col_ids),
)
block = self._block.order_by(
[order.ascending_over(col) for col in self._by_col_ids],
)
return windows.Window(
block,
window_spec,
[self._value_column],
drop_null_groups=self._dropna,
is_series=True,
)
return rolling.create_range_window(
self._block,
window,
min_periods=min_periods,
value_column_ids=[self._value_column],
closed=closed,
is_series=True,
grouping_keys=self._by_col_ids,
drop_null_groups=self._dropna,
)
@validations.requires_ordering()
def expanding(self, min_periods: int = 1) -> windows.Window:
window_spec = window_specs.cumulative_rows(
grouping_keys=tuple(self._by_col_ids),
min_periods=min_periods,
)
block = self._block.order_by(
[order.ascending_over(col) for col in self._by_col_ids],
)
return windows.Window(
block,
window_spec,
[self._value_column],
drop_null_groups=self._dropna,
is_series=True,
)
def _aggregate(self, aggregate_op: agg_ops.UnaryAggregateOp) -> series.Series:
result_block, _ = self._block.aggregate(
self._by_col_ids,
(aggs.agg(self._value_column, aggregate_op),),
dropna=self._dropna,
)
return series.Series(result_block.with_column_labels([self._value_name]))
def _apply_window_op(
self,
op: agg_ops.UnaryWindowOp,
discard_name=False,
window: typing.Optional[window_specs.WindowSpec] = None,
never_skip_nulls: bool = False,
) -> series.Series:
"""Apply window op to groupby. Defaults to grouped cumulative window."""
window_spec = window or window_specs.cumulative_rows(
grouping_keys=tuple(self._by_col_ids)
)
label = self._value_name if not discard_name else None
block, result_id = self._block.apply_window_op(
self._value_column,
op,
result_label=label,
window_spec=window_spec,
never_skip_nulls=never_skip_nulls,
)
return series.Series(block.select_column(result_id))