/
resample.py
399 lines (348 loc) · 12.5 KB
/
resample.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
# Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you 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.
"""Implement Resampler public API."""
from typing import Optional
import numpy as np
import pandas
import pandas.core.resample
from pandas._libs import lib
from pandas.core.dtypes.common import is_list_like
from modin.logging import ClassLogger
from modin.pandas.utils import cast_function_modin2pandas
from modin.utils import _inherit_docstrings
@_inherit_docstrings(pandas.core.resample.Resampler)
class Resampler(ClassLogger):
def __init__(
self,
dataframe,
rule,
axis=0,
closed=None,
label=None,
convention="start",
kind=None,
on=None,
level=None,
origin="start_day",
offset=None,
group_keys=lib.no_default,
):
self._dataframe = dataframe
self._query_compiler = dataframe._query_compiler
self.axis = self._dataframe._get_axis_number(axis)
self.resample_kwargs = {
"rule": rule,
"axis": axis,
"closed": closed,
"label": label,
"convention": convention,
"kind": kind,
"on": on,
"level": level,
"origin": origin,
"offset": offset,
"group_keys": group_keys,
}
self.__groups = self._get_groups()
def _get_groups(self):
"""
Compute the resampled groups.
Returns
-------
PandasGroupby
Groups as specified by resampling arguments.
"""
df = self._dataframe if self.axis == 0 else self._dataframe.T
groups = df.groupby(
pandas.Grouper(
key=self.resample_kwargs["on"],
freq=self.resample_kwargs["rule"],
closed=self.resample_kwargs["closed"],
label=self.resample_kwargs["label"],
convention=self.resample_kwargs["convention"],
level=self.resample_kwargs["level"],
origin=self.resample_kwargs["origin"],
offset=self.resample_kwargs["offset"],
),
group_keys=self.resample_kwargs["group_keys"],
)
return groups
def __getitem__(self, key):
"""
Get ``Resampler`` based on `key` columns of original dataframe.
Parameters
----------
key : str or list
String or list of selections.
Returns
-------
modin.pandas.BasePandasDataset
New ``Resampler`` based on `key` columns subset
of the original dataframe.
"""
def _get_new_resampler(key):
subset = self._dataframe[key]
resampler = type(self)(subset, **self.resample_kwargs)
return resampler
from .series import Series
if isinstance(
key, (list, tuple, Series, pandas.Series, pandas.Index, np.ndarray)
):
if len(self._dataframe.columns.intersection(key)) != len(set(key)):
missed_keys = list(set(key).difference(self._dataframe.columns))
raise KeyError(f"Columns not found: {str(sorted(missed_keys))[1:-1]}")
return _get_new_resampler(list(key))
if key not in self._dataframe:
raise KeyError(f"Column not found: {key}")
return _get_new_resampler(key)
@property
def groups(self):
return self._query_compiler.default_to_pandas(
lambda df: pandas.DataFrame.resample(df, **self.resample_kwargs).groups
)
@property
def indices(self):
return self._query_compiler.default_to_pandas(
lambda df: pandas.DataFrame.resample(df, **self.resample_kwargs).indices
)
def get_group(self, name, obj=None):
return self._dataframe.__constructor__(
query_compiler=self._query_compiler.resample_get_group(
self.resample_kwargs, name, obj
)
)
def apply(self, func, *args, **kwargs):
func = cast_function_modin2pandas(func)
from .dataframe import DataFrame
if isinstance(self._dataframe, DataFrame):
query_comp_op = self._query_compiler.resample_app_df
else:
query_comp_op = self._query_compiler.resample_app_ser
dataframe = DataFrame(
query_compiler=query_comp_op(
self.resample_kwargs,
func,
*args,
**kwargs,
)
)
if is_list_like(func) or isinstance(self._dataframe, DataFrame):
return dataframe
else:
if len(dataframe.index) == 1:
return dataframe.iloc[0]
else:
return dataframe.squeeze()
def aggregate(self, func, *args, **kwargs):
from .dataframe import DataFrame
if isinstance(self._dataframe, DataFrame):
query_comp_op = self._query_compiler.resample_agg_df
else:
query_comp_op = self._query_compiler.resample_agg_ser
dataframe = DataFrame(
query_compiler=query_comp_op(
self.resample_kwargs,
func,
*args,
**kwargs,
)
)
if is_list_like(func) or isinstance(self._dataframe, DataFrame):
return dataframe
else:
if len(dataframe.index) == 1:
return dataframe.iloc[0]
else:
return dataframe.squeeze()
def transform(self, arg, *args, **kwargs):
return self._dataframe.__constructor__(
query_compiler=self._query_compiler.resample_transform(
self.resample_kwargs, arg, *args, **kwargs
)
)
def pipe(self, func, *args, **kwargs):
return self._dataframe.__constructor__(
query_compiler=self._query_compiler.resample_pipe(
self.resample_kwargs, func, *args, **kwargs
)
)
def ffill(self, limit=None):
return self.fillna(method="ffill", limit=limit)
def bfill(self, limit=None):
return self.fillna(method="bfill", limit=limit)
def nearest(self, limit=None):
return self._dataframe.__constructor__(
query_compiler=self._query_compiler.resample_nearest(
self.resample_kwargs, limit
)
)
def fillna(self, method, limit=None):
return self._dataframe.__constructor__(
query_compiler=self._query_compiler.resample_fillna(
self.resample_kwargs, method, limit
)
)
def asfreq(self, fill_value=None):
return self._dataframe.__constructor__(
query_compiler=self._query_compiler.resample_asfreq(
self.resample_kwargs, fill_value
)
)
def interpolate(
self,
method="linear",
*,
axis=0,
limit=None,
inplace=False,
limit_direction: Optional[str] = None,
limit_area=None,
downcast=lib.no_default,
**kwargs,
):
return self._dataframe.__constructor__(
query_compiler=self._query_compiler.resample_interpolate(
self.resample_kwargs,
method,
axis=axis,
limit=limit,
inplace=inplace,
limit_direction=limit_direction,
limit_area=limit_area,
downcast=downcast,
**kwargs,
)
)
def count(self):
return self._dataframe.__constructor__(
query_compiler=self._query_compiler.resample_count(self.resample_kwargs)
)
def nunique(self, *args, **kwargs):
return self._dataframe.__constructor__(
query_compiler=self._query_compiler.resample_nunique(
self.resample_kwargs, *args, **kwargs
)
)
def first(self, *args, **kwargs):
return self._dataframe.__constructor__(
query_compiler=self._query_compiler.resample_first(
self.resample_kwargs,
*args,
**kwargs,
)
)
def last(self, *args, **kwargs):
return self._dataframe.__constructor__(
query_compiler=self._query_compiler.resample_last(
self.resample_kwargs,
*args,
**kwargs,
)
)
def max(self, *args, **kwargs):
return self._dataframe.__constructor__(
query_compiler=self._query_compiler.resample_max(
self.resample_kwargs,
*args,
**kwargs,
)
)
def mean(self, *args, **kwargs):
return self._dataframe.__constructor__(
query_compiler=self._query_compiler.resample_mean(
self.resample_kwargs,
*args,
**kwargs,
)
)
def median(self, *args, **kwargs):
return self._dataframe.__constructor__(
query_compiler=self._query_compiler.resample_median(
self.resample_kwargs,
*args,
**kwargs,
)
)
def min(self, *args, **kwargs):
return self._dataframe.__constructor__(
query_compiler=self._query_compiler.resample_min(
self.resample_kwargs,
*args,
**kwargs,
)
)
def ohlc(self, *args, **kwargs):
from .dataframe import DataFrame
if isinstance(self._dataframe, DataFrame):
return DataFrame(
query_compiler=self._query_compiler.resample_ohlc_df(
self.resample_kwargs,
*args,
**kwargs,
)
)
else:
return DataFrame(
query_compiler=self._query_compiler.resample_ohlc_ser(
self.resample_kwargs,
*args,
**kwargs,
)
)
def prod(self, min_count=0, *args, **kwargs):
return self._dataframe.__constructor__(
query_compiler=self._query_compiler.resample_prod(
self.resample_kwargs, min_count=min_count, *args, **kwargs
)
)
def size(self):
from .series import Series
output_series = Series(
query_compiler=self._query_compiler.resample_size(self.resample_kwargs)
)
if not isinstance(self._dataframe, Series):
# If input is a DataFrame, rename output Series to None
return output_series.rename(None)
return output_series
def sem(self, *args, **kwargs):
return self._dataframe.__constructor__(
query_compiler=self._query_compiler.resample_sem(
self.resample_kwargs,
*args,
**kwargs,
)
)
def std(self, ddof=1, *args, **kwargs):
return self._dataframe.__constructor__(
query_compiler=self._query_compiler.resample_std(
self.resample_kwargs, *args, ddof=ddof, **kwargs
)
)
def sum(self, min_count=0, *args, **kwargs):
return self._dataframe.__constructor__(
query_compiler=self._query_compiler.resample_sum(
self.resample_kwargs, min_count=min_count, *args, **kwargs
)
)
def var(self, ddof=1, *args, **kwargs):
return self._dataframe.__constructor__(
query_compiler=self._query_compiler.resample_var(
self.resample_kwargs, *args, ddof=ddof, **kwargs
)
)
def quantile(self, q=0.5, **kwargs):
return self._dataframe.__constructor__(
query_compiler=self._query_compiler.resample_quantile(
self.resample_kwargs, q, **kwargs
)
)