-
Notifications
You must be signed in to change notification settings - Fork 143
/
groupby.py
319 lines (260 loc) · 10.9 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
#
# Copyright (c) 2021, NVIDIA CORPORATION.
#
# 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.
import re
import numpy
from dask.dataframe.utils import meta_nonempty
from merlin.core.dispatch import DataFrameType, annotate
from merlin.dtypes.shape import DefaultShapes
from merlin.schema import Schema
from nvtabular.ops.operator import ColumnSelector, Operator
class Groupby(Operator):
"""Groupby Transformation
Locally transform each partition of a Dataset with one or
more groupby aggregations.
WARNING: This transformation does NOT move data between
partitions. Please make sure that the target Dataset object
is already shuffled by ``groupby_cols``, otherwise the
output may be incorrect. See: ``Dataset.shuffle_by_keys``.
Example usage::
groupby_cols = ['user_id', 'session_id']
dataset = dataset.shuffle_by_keys(keys=groupby_cols)
groupby_features = [
'user_id', 'session_id', 'month', 'prod_id',
] >> ops.Groupby(
groupby_cols=groupby_cols,
sort_cols=['month'],
aggs={
'prod_id': 'list',
'month': ['first', 'last'],
},
)
processor = nvtabular.Workflow(groupby_features)
workflow.fit(dataset)
dataset_transformed = workflow.transform(dataset)
Parameters
-----------
groupby_cols : str or list of str
The column names to be used as groupby keys.
WARNING: Ensure the dataset was partitioned by those
groupby keys (see above for an example).
sort_cols : str or list of str
Columns to be used to sort each partition before
groupby aggregation is performed. If this argument
is not specified, the results will not be sorted.
aggs : dict, list or str
Groupby aggregations to perform. Supported list-based
aggregations include "list", "first" & "last". Most
conventional aggregations supported by Pandas/cuDF are
also allowed (e.g. "sum", "count", "max", "mean", etc.).
name_sep : str
String separator to use for new column names.
"""
def __init__(
self, groupby_cols=None, sort_cols=None, aggs="list", name_sep="_", ascending=True
):
self.groupby_cols = groupby_cols
self.sort_cols = sort_cols or []
if isinstance(self.groupby_cols, str):
self.groupby_cols = [self.groupby_cols]
if isinstance(self.sort_cols, str):
self.sort_cols = [self.sort_cols]
self.ascending = ascending
# Split aggregations into "conventional" aggregations
# and "list-based" aggregations. After this block,
# we will have a dictionary for each of these cases.
# We use the "__all__" key to specify aggregations
# that will be performed on all (non-key) columns.
self.list_aggs, self.conv_aggs = {}, {}
if isinstance(aggs, str):
aggs = {"__all__": [aggs]}
elif isinstance(aggs, list):
aggs = {"__all__": aggs}
for col, v in aggs.items():
_aggs = v if isinstance(v, list) else [v]
_conv_aggs, _list_aggs = set(), set()
for _agg in _aggs:
if is_list_agg(_agg):
_list_aggs.add("list" if _agg == list else _agg)
_conv_aggs.add(list)
else:
_conv_aggs.add(_agg)
if _conv_aggs:
self.conv_aggs[col] = list(_conv_aggs)
if _list_aggs:
self.list_aggs[col] = list(_list_aggs)
self.name_sep = name_sep
super().__init__()
@annotate("Groupby_op", color="darkgreen", domain="nvt_python")
def transform(self, col_selector: ColumnSelector, df: DataFrameType) -> DataFrameType:
# Sort if necessary
if self.sort_cols:
df = df.sort_values(self.sort_cols, ascending=self.ascending, ignore_index=True)
# List aggregations do not work with empty data.
# Use synthetic metadata to predict output columns.
empty_df = not len(df)
_df = meta_nonempty(df) if empty_df else df
# Get "complete" aggregation dicts
_list_aggs, _conv_aggs = _get_agg_dicts(
self.groupby_cols, self.list_aggs, self.conv_aggs, col_selector
)
# Apply aggregations
new_df = _apply_aggs(
_df,
self.groupby_cols,
_list_aggs,
_conv_aggs,
name_sep=self.name_sep,
ascending=self.ascending,
)
if empty_df:
return new_df.iloc[:0]
return new_df
transform.__doc__ = Operator.transform.__doc__
def compute_output_schema(
self, input_schema: Schema, col_selector: ColumnSelector, prev_output_schema: Schema = None
) -> Schema:
if not col_selector and hasattr(self, "target"):
col_selector = (
ColumnSelector(self.target) if isinstance(self.target, list) else self.target
)
return super().compute_output_schema(input_schema, col_selector, prev_output_schema)
def column_mapping(self, col_selector):
column_mapping = {}
for groupby_col in self.groupby_cols:
if groupby_col in col_selector.names:
column_mapping[groupby_col] = [groupby_col]
_list_aggs, _conv_aggs = _get_agg_dicts(
self.groupby_cols, self.list_aggs, self.conv_aggs, col_selector
)
for input_col_name, aggs in _list_aggs.items():
output_col_names = _columns_out_from_aggs(
{input_col_name: aggs}, name_sep=self.name_sep
)
for output_col_name in output_col_names:
column_mapping[output_col_name] = [input_col_name]
for input_col_name, aggs in _conv_aggs.items():
output_col_names = _columns_out_from_aggs(
{input_col_name: aggs}, name_sep=self.name_sep
)
for output_col_name in output_col_names:
column_mapping[output_col_name] = [input_col_name]
return column_mapping
@property
def dependencies(self):
return self.groupby_cols
def _compute_dtype(self, col_schema, input_schema):
col_schema = super()._compute_dtype(col_schema, input_schema)
agg_dtypes = {
"count": numpy.int32,
"nunique": numpy.int32,
"mean": numpy.float32,
"var": numpy.float32,
"std": numpy.float32,
"median": numpy.float32,
"sum": numpy.float32,
}
agg = self._find_agg(col_schema, input_schema)
dtype = agg_dtypes.get(agg, col_schema.dtype)
return col_schema.with_dtype(dtype)
def _compute_shape(self, col_schema, input_schema):
agg_is_lists = {"list": True}
agg = self._find_agg(col_schema, input_schema)
is_list = agg_is_lists.get(agg, col_schema.is_list)
shape = DefaultShapes.LIST if is_list else DefaultShapes.SCALAR
return col_schema.with_shape(shape)
def _find_agg(self, col_schema, input_schema):
input_selector = ColumnSelector(input_schema.column_names)
column_mapping = self.column_mapping(input_selector)
input_column_name = column_mapping[col_schema.name][0]
agg = col_schema.name.replace(input_column_name, "").lstrip(self.name_sep)
return agg
def _aggs_for_column(col_name, agg_dict):
return agg_dict.get(col_name, []) + agg_dict.get("__all__", [])
def _columns_out_from_aggs(aggs, name_sep="_"):
# Helper function for `output_column_names`
_agg_cols = []
for k, v in aggs.items():
for _v in v:
if isinstance(_v, str):
_agg_cols.append(name_sep.join([k, _v]))
return _agg_cols
def _apply_aggs(_df, groupby_cols, _list_aggs, _conv_aggs, name_sep="_", ascending=True):
# Apply conventional aggs
_columns = list(set(groupby_cols) | set(_conv_aggs) | set(_list_aggs))
df = _df[_columns].groupby(groupby_cols).agg(_conv_aggs).reset_index()
df.columns = [
name_sep.join([n for n in name if n != ""]) for name in df.columns.to_flat_index()
]
# Handle custom aggs (e.g. "first" and "last")
for col, aggs in _list_aggs.items():
for _agg in aggs:
if is_list_agg(_agg, custom=True):
df[f"{col}{name_sep}{_agg}"] = _first_or_last(
df[f"{col}{name_sep}list"], _agg, ascending=ascending
)
if "list" not in aggs:
df.drop(columns=[col + f"{name_sep}list"], inplace=True)
for col in df.columns:
if re.search(f"{name_sep}(count|nunique)$", col):
df[col] = df[col].astype(numpy.int32)
elif re.search(f"{name_sep}(mean|median|std|var|sum)$", col):
df[col] = df[col].astype(numpy.float32)
return df
def _get_agg_dicts(groupby_cols, list_aggs, conv_aggs, columns):
# Get updated aggregation dicts. This should map "__all__"
# to specific columns, and remove elements that are not
# in `columns`.
_allowed_cols = [c for c in columns.names if c not in groupby_cols]
_list_aggs = _ensure_agg_dict(list_aggs, _allowed_cols)
_conv_aggs = _ensure_agg_dict(conv_aggs, _allowed_cols)
return _list_aggs, _conv_aggs
def _ensure_agg_dict(_aggs, _allowed_cols):
# Make sure aggregation dict has legal keys
if "__all__" in _aggs:
return {col: _aggs["__all__"] for col in _allowed_cols}
else:
return {k: v for k, v in _aggs.items() if k in _allowed_cols}
def is_list_agg(agg, custom=False):
# check if `agg` is a supported list aggregation
if custom:
return agg in ("first", "last")
else:
return agg in ("list", list, "first", "last")
def _first_or_last(x, kind, ascending=True):
# Redirect to _first or _last
if kind == "first" and ascending:
return _first(x)
elif kind == "last" and not ascending:
return _first(x)
else:
return _last(x)
def _first(x):
# Convert each element of a list column to be the first
# item in the list
if hasattr(x, "list"):
# cuDF-specific behavior
return x.list.get(0)
else:
# cpu/pandas
return x.apply(lambda y: y[0])
def _last(x):
# Convert each element of a list column to be the last
# item in the list
if hasattr(x, "list"):
# cuDF-specific behavior
return x.list.get(-1)
else:
# cpu/pandas
return x.apply(lambda y: y[-1])