-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathbase_overrides.py
More file actions
2405 lines (2098 loc) · 79.6 KB
/
base_overrides.py
File metadata and controls
2405 lines (2098 loc) · 79.6 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
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
#
# Copyright (c) 2012-2025 Snowflake Computing Inc. All rights reserved.
#
"""
Methods defined on BasePandasDataset that are overridden in Snowpark pandas. Adding a method to this file
should be done with discretion, and only when relevant changes cannot be made to the query compiler or
upstream frontend to accommodate Snowpark pandas.
If you must override a method in this file, please add a comment describing why it must be overridden,
and if possible, whether this can be reconciled with upstream Modin.
"""
from __future__ import annotations
import functools
import pickle as pkl
import warnings
from collections.abc import Sequence
from typing import Any, Callable, Hashable, Literal, Mapping, get_args
import modin.pandas as pd
import numpy as np
import numpy.typing as npt
import pandas
from modin.core.storage_formats.pandas.query_compiler_caster import (
register_function_for_pre_op_switch,
)
from modin.pandas import Series
from modin.pandas.api.extensions import register_base_accessor
from modin.pandas.base import BasePandasDataset
from modin.pandas.utils import is_scalar
from pandas._libs import lib
from pandas._libs.lib import NoDefault, is_bool, no_default
from pandas._typing import (
AggFuncType,
AnyArrayLike,
Axes,
Axis,
CompressionOptions,
FillnaOptions,
IgnoreRaise,
IndexKeyFunc,
IndexLabel,
Level,
NaPosition,
RandomState,
Scalar,
StorageOptions,
TimedeltaConvertibleTypes,
TimestampConvertibleTypes,
)
from pandas.core.common import apply_if_callable
from pandas.core.dtypes.common import (
is_dict_like,
is_dtype_equal,
is_list_like,
is_numeric_dtype,
pandas_dtype,
)
from pandas.core.dtypes.inference import is_integer
from pandas.core.methods.describe import _refine_percentiles
from pandas.errors import SpecificationError
from pandas.util._validators import (
validate_ascending,
validate_bool_kwarg,
validate_percentile,
)
from snowflake.snowpark.modin.plugin._typing import ListLike
from snowflake.snowpark.modin.plugin.compiler.snowflake_query_compiler import (
HYBRID_SWITCH_FOR_UNIMPLEMENTED_METHODS,
)
from snowflake.snowpark.modin.plugin._internal.utils import new_snow_series
from snowflake.snowpark.modin.plugin.extensions.utils import (
ensure_index,
extract_validate_and_try_convert_named_aggs_from_kwargs,
get_as_shape_compatible_dataframe_or_series,
raise_if_native_pandas_objects,
validate_and_try_convert_agg_func_arg_func_to_str,
)
from snowflake.snowpark.modin.plugin.utils.error_message import (
ErrorMessage,
base_not_implemented,
)
from snowflake.snowpark.modin.plugin.utils.warning_message import (
WarningMessage,
materialization_warning,
)
from snowflake.snowpark.modin.utils import validate_int_kwarg
_TIMEDELTA_PCT_CHANGE_AXIS_1_MIXED_TYPE_ERROR_MESSAGE = (
"pct_change(axis=1) is invalid when one column is Timedelta another column is not."
)
register_base_override = functools.partial(register_base_accessor, backend="Snowflake")
def register_base_not_implemented():
def decorator(base_method: Any):
name = base_method.__name__
HYBRID_SWITCH_FOR_UNIMPLEMENTED_METHODS.add(("BasePandasDataset", name))
register_function_for_pre_op_switch(
class_name="BasePandasDataset", backend="Snowflake", method=name
)
return register_base_override(name=name)(base_not_implemented()(base_method))
return decorator
# === UNIMPLEMENTED METHODS ===
# The following methods are not implemented in Snowpark pandas, and must be overridden on the
# frontend. These methods fall into a few categories:
# 1. Would work in Snowpark pandas, but we have not tested it.
# 2. Would work in Snowpark pandas, but requires more SQL queries than we are comfortable with.
# 3. Requires materialization (usually via a frontend _default_to_pandas call).
# 4. Performs operations on a native pandas Index object that are nontrivial for Snowpark pandas to manage.
@register_base_not_implemented()
def asof(self, where, subset=None): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def at_time(self, time, asof=False, axis=None): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def between_time(
self: BasePandasDataset,
start_time,
end_time,
inclusive: str | None = None,
axis=None,
): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def bool(self): # noqa: RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def clip(
self, lower=None, upper=None, axis=None, inplace=False, *args, **kwargs
): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def combine(self, other, func, fill_value=None, **kwargs): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def combine_first(self, other): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def droplevel(self, level, axis=0): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def explode(self, column, ignore_index: bool = False): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def ewm(
self,
com: float | None = None,
span: float | None = None,
halflife: float | TimedeltaConvertibleTypes | None = None,
alpha: float | None = None,
min_periods: int | None = 0,
adjust: bool = True,
ignore_na: bool = False,
axis: Axis = 0,
times: str | np.ndarray | BasePandasDataset | None = None,
method: str = "single",
) -> pandas.core.window.ewm.ExponentialMovingWindow: # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def filter(
self, items=None, like=None, regex=None, axis=None
): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def infer_objects(self, copy: bool | None = None): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def interpolate(
self,
method="linear",
*,
axis=0,
limit=None,
inplace=False,
limit_direction: str | None = None,
limit_area=None,
downcast=lib.no_default,
**kwargs,
): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def kurt(
self, axis=no_default, skipna=True, numeric_only=False, **kwargs
): # noqa: PR01, RT01, D200
pass # pragma: no cover
register_base_override("kurtosis")(kurt)
@register_base_not_implemented()
def mode(self, axis=0, numeric_only=False, dropna=True): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def pipe(self, func, *args, **kwargs): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def reindex_like(
self, other, method=None, copy=True, limit=None, tolerance=None
): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def reorder_levels(self, order, axis=0): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def sem(
self,
axis: Axis | None = None,
skipna: bool = True,
ddof: int = 1,
numeric_only=False,
**kwargs,
): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def set_flags(
self, *, copy: bool = False, allows_duplicate_labels: bool | None = None
): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def swapaxes(self, axis1, axis2, copy=True): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def swaplevel(self, i=-2, j=-1, axis=0): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def to_clipboard(
self, excel=True, sep=None, **kwargs
): # pragma: no cover # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def to_hdf(
self, path_or_buf, key, format="table", **kwargs
): # pragma: no cover # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def to_json(
self,
path_or_buf=None,
orient=None,
date_format=None,
double_precision=10,
force_ascii=True,
date_unit="ms",
default_handler=None,
lines=False,
compression="infer",
index=True,
indent=None,
storage_options: StorageOptions = None,
): # pragma: no cover # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def to_latex(
self,
buf=None,
columns=None,
col_space=None,
header=True,
index=True,
na_rep="NaN",
formatters=None,
float_format=None,
sparsify=None,
index_names=True,
bold_rows=False,
column_format=None,
longtable=None,
escape=None,
encoding=None,
decimal=".",
multicolumn=None,
multicolumn_format=None,
multirow=None,
caption=None,
label=None,
position=None,
): # pragma: no cover # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def to_markdown(
self,
buf=None,
mode: str = "wt",
index: bool = True,
storage_options: StorageOptions = None,
**kwargs,
): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def to_pickle(
self,
path,
compression: CompressionOptions = "infer",
protocol: int = pkl.HIGHEST_PROTOCOL,
storage_options: StorageOptions = None,
): # pragma: no cover # noqa: PR01, D200
pass # pragma: no cover
@register_base_not_implemented()
def to_sql(
self,
name,
con,
schema=None,
if_exists="fail",
index=True,
index_label=None,
chunksize=None,
dtype=None,
method=None,
): # noqa: PR01, D200
pass # pragma: no cover
@register_base_not_implemented()
def to_timestamp(
self, freq=None, how="start", axis=0, copy=True
): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def to_xarray(self): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def transform(self, func, axis=0, *args, **kwargs): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def truncate(
self, before=None, after=None, axis=None, copy=True
): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def xs(
self,
key,
axis=0,
level=None,
drop_level: bool = True,
): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_base_not_implemented()
def __finalize__(self, other, method=None, **kwargs):
pass # pragma: no cover
@register_base_not_implemented()
def __sizeof__(self):
pass # pragma: no cover
# === OVERRIDDEN METHODS ===
# The below methods have their frontend implementations overridden compared to the version present
# in base.py. This is usually for one of the following reasons:
# 1. The underlying QC interface used differs from that of modin. Notably, this applies to aggregate
# and binary operations; further work is needed to refactor either our implementation or upstream
# modin's implementation.
# 2. Modin performs extra validation queries that perform extra SQL queries. Some of these are already
# fixed on main; see https://github.com/modin-project/modin/issues/7340 for details.
# 3. Upstream Modin defaults to pandas for some edge cases. Defaulting to pandas at the query compiler
# layer is acceptable because we can force the method to raise NotImplementedError, but if a method
# defaults at the frontend, Modin raises a warning and performs the operation by coercing the
# dataset to a native pandas object. Removing these is tracked by
# https://github.com/modin-project/modin/issues/7104
# 4. Snowpark pandas uses different default arguments from modin. This occurs if some parameters are
# only partially supported (like `numeric_only=True` for `skew`), but this behavior should likewise
# be revisited.
# `aggregate` for axis=1 is performed as a call to `BasePandasDataset.apply` in upstream Modin,
# which is unacceptable for Snowpark pandas. Upstream Modin should be changed to allow the query
# compiler or a different layer to control dispatch.
@register_base_override("aggregate")
def aggregate(
self, func: AggFuncType = None, axis: Axis | None = 0, *args: Any, **kwargs: Any
):
"""
Aggregate using one or more operations over the specified axis.
"""
# TODO: SNOW-1119855: Modin upgrade - modin.pandas.base.BasePandasDataset
origin_axis = axis
axis = self._get_axis_number(axis)
if axis == 1 and isinstance(self, Series):
raise ValueError(f"No axis named {origin_axis} for object type Series")
if len(self._query_compiler.columns) == 0:
# native pandas raise error with message "no result", here we raise a more readable error.
raise ValueError("No column to aggregate on.")
# If we are using named kwargs, then we do not clear the kwargs (need them in the QC for processing
# order, as well as formatting error messages.)
uses_named_kwargs = False
# If aggregate is called on a Series, named aggregations can be passed in via a dictionary
# to func.
if func is None or (is_dict_like(func) and not self._is_dataframe):
if axis == 1:
raise ValueError(
"`func` must not be `None` when `axis=1`. Named aggregations are not supported with `axis=1`."
)
if func is not None:
# If named aggregations are passed in via a dictionary to func, then we
# ignore the kwargs.
if any(is_dict_like(value) for value in func.values()):
# We can only get to this codepath if self is a Series, and func is a dictionary.
# In this case, if any of the values of func are themselves dictionaries, we must raise
# a Specification Error, as that is what pandas does.
raise SpecificationError("nested renamer is not supported")
kwargs = func
func = extract_validate_and_try_convert_named_aggs_from_kwargs(
self, allow_duplication=False, axis=axis, **kwargs
)
uses_named_kwargs = True
else:
func = validate_and_try_convert_agg_func_arg_func_to_str(
agg_func=func,
obj=self,
allow_duplication=False,
axis=axis,
)
# This is to stay consistent with pandas result format, when the func is single
# aggregation function in format of callable or str, reduce the result dimension to
# convert dataframe to series, or convert series to scalar.
# Note: When named aggregations are used, the result is not reduced, even if there
# is only a single function.
# needs_reduce_dimension cannot be True if we are using named aggregations, since
# the values for func in that case are either NamedTuples (AggFuncWithLabels) or
# lists of NamedTuples, both of which are list like.
need_reduce_dimension = (
(callable(func) or isinstance(func, str))
# A Series should be returned when a single scalar string/function aggregation function, or a
# dict of scalar string/functions is specified. In all other cases (including if the function
# is a 1-element list), the result is a DataFrame.
#
# The examples below have axis=1, but the same logic is applied for axis=0.
# >>> df = pd.DataFrame({"a": [0, 1], "b": [2, 3]})
#
# single aggregation: return Series
# >>> df.agg("max", axis=1)
# 0 2
# 1 3
# dtype: int64
#
# list of aggregations: return DF
# >>> df.agg(["max"], axis=1)
# max
# 0 2
# 1 3
#
# dict where all aggregations are strings: return Series
# >>> df.agg({1: "max", 0: "min"}, axis=1)
# 1 3
# 0 0
# dtype: int64
#
# dict where one element is a list: return DF
# >>> df.agg({1: "max", 0: ["min"]}, axis=1)
# max min
# 1 3.0 NaN
# 0 NaN 0.0
or (
is_dict_like(func)
and all(not is_list_like(value) for value in func.values())
)
)
# If func is a dict, pandas will not respect kwargs for each aggregation function, and
# we should drop them before passing the to the query compiler.
#
# >>> native_pd.DataFrame({"a": [0, 1], "b": [np.nan, 0]}).agg("max", skipna=False, axis=1)
# 0 NaN
# 1 1.0
# dtype: float64
# >>> native_pd.DataFrame({"a": [0, 1], "b": [np.nan, 0]}).agg(["max"], skipna=False, axis=1)
# max
# 0 0.0
# 1 1.0
# >>> pd.DataFrame([[np.nan], [0]]).aggregate("count", skipna=True, axis=0)
# 0 1
# dtype: int8
# >>> pd.DataFrame([[np.nan], [0]]).count(skipna=True, axis=0)
# TypeError: got an unexpected keyword argument 'skipna'
if is_dict_like(func) and not uses_named_kwargs:
kwargs.clear()
result = self.__constructor__(
query_compiler=self._query_compiler.agg(
func=func,
axis=axis,
args=args,
kwargs=kwargs,
)
)
if need_reduce_dimension:
if self._is_dataframe:
result = Series(query_compiler=result._query_compiler)
if isinstance(result, Series):
# When func is just "quantile" with a scalar q, result has quantile value as name
q = kwargs.get("q", 0.5)
if func == "quantile" and is_scalar(q):
result.name = q
else:
result.name = None
# handle case for single scalar (same as result._reduce_dimension())
if isinstance(self, Series):
return result.to_pandas().squeeze()
return result
# `agg` is an alias of `aggregate`.
agg = aggregate
register_base_override("agg")(agg)
# `_agg_helper` is not defined in modin, and used by Snowpark pandas to do extra validation.
@register_base_override("_agg_helper")
def _agg_helper(
self,
func: str,
skipna: bool = True,
axis: int | None | NoDefault = no_default,
numeric_only: bool = False,
**kwargs: Any,
):
if not self._is_dataframe and numeric_only and not is_numeric_dtype(self.dtype):
# Series aggregations on non-numeric data do not support numeric_only:
# https://github.com/pandas-dev/pandas/blob/cece8c6579854f6b39b143e22c11cac56502c4fd/pandas/core/series.py#L6358
raise TypeError(
f"Series.{func} does not allow numeric_only=True with non-numeric dtypes."
)
axis = self._get_axis_number(axis)
numeric_only = validate_bool_kwarg(numeric_only, "numeric_only", none_allowed=True)
skipna = validate_bool_kwarg(skipna, "skipna", none_allowed=False)
agg_kwargs: dict[str, Any] = {
"numeric_only": numeric_only,
"skipna": skipna,
}
agg_kwargs.update(kwargs)
return self.aggregate(func=func, axis=axis, **agg_kwargs)
# See _agg_helper
@register_base_override("count")
def count(
self,
axis: Axis | None = 0,
numeric_only: bool = False,
):
"""
Count non-NA cells for `BasePandasDataset`.
"""
# TODO: SNOW-1119855: Modin upgrade - modin.pandas.base.BasePandasDataset
return self._agg_helper(
func="count",
axis=axis,
numeric_only=numeric_only,
)
# See _agg_helper
@register_base_override("max")
def max(
self,
axis: Axis | None = 0,
skipna: bool = True,
numeric_only: bool = False,
**kwargs: Any,
):
"""
Return the maximum of the values over the requested axis.
"""
return self._agg_helper(
func="max",
axis=axis,
skipna=skipna,
numeric_only=numeric_only,
**kwargs,
)
# See _agg_helper
@register_base_override("min")
def min(
self,
axis: Axis | None | NoDefault = no_default,
skipna: bool = True,
numeric_only: bool = False,
**kwargs,
):
"""
Return the minimum of the values over the requested axis.
"""
# TODO: SNOW-1119855: Modin upgrade - modin.pandas.base.BasePandasDataset
return self._agg_helper(
func="min",
axis=axis,
skipna=skipna,
numeric_only=numeric_only,
**kwargs,
)
# See _agg_helper
@register_base_override("mean")
def mean(
self,
axis: Axis | None | NoDefault = no_default,
skipna: bool = True,
numeric_only: bool = False,
**kwargs: Any,
):
"""
Return the mean of the values over the requested axis.
"""
return self._agg_helper(
func="mean",
axis=axis,
skipna=skipna,
numeric_only=numeric_only,
**kwargs,
)
# See _agg_helper
@register_base_override("median")
def median(
self,
axis: Axis | None | NoDefault = no_default,
skipna: bool = True,
numeric_only: bool = False,
**kwargs: Any,
):
"""
Return the mean of the values over the requested axis.
"""
return self._agg_helper(
func="median",
axis=axis,
skipna=skipna,
numeric_only=numeric_only,
**kwargs,
)
# See _agg_helper
@register_base_override("std")
def std(
self,
axis: Axis | None = None,
skipna: bool = True,
ddof: int = 1,
numeric_only: bool = False,
**kwargs,
):
"""
Return sample standard deviation over requested axis.
"""
# TODO: SNOW-1119855: Modin upgrade - modin.pandas.base.BasePandasDataset
kwargs.update({"ddof": ddof})
return self._agg_helper(
func="std",
axis=axis,
skipna=skipna,
numeric_only=numeric_only,
**kwargs,
)
# See _agg_helper
@register_base_override("var")
def var(
self,
axis: Axis | None = None,
skipna: bool = True,
ddof: int = 1,
numeric_only: bool = False,
**kwargs: Any,
):
"""
Return unbiased variance over requested axis.
"""
kwargs.update({"ddof": ddof})
return self._agg_helper(
func="var",
axis=axis,
skipna=skipna,
numeric_only=numeric_only,
**kwargs,
)
@register_base_override("align")
def align(
self,
other: BasePandasDataset,
join: str = "outer",
axis: Axis = None,
level: Level = None,
copy: bool = True,
fill_value: Scalar = None,
method: str = None,
limit: int = None,
fill_axis: Axis = 0,
broadcast_axis: Axis = None,
): # noqa: PR01, RT01, D200
from modin.pandas.dataframe import DataFrame
if method is not None or limit is not None or fill_axis != 0:
raise NotImplementedError(
f"The 'method', 'limit', and 'fill_axis' keywords in {self.__class__.__name__}.align are deprecated and will be removed in a future version. Call fillna directly on the returned objects instead."
)
if broadcast_axis is not None:
raise NotImplementedError(
f"The 'broadcast_axis' keyword in {self.__class__.__name__}.align is deprecated and will be removed in a future version."
)
if axis not in [0, 1, None]:
raise ValueError(
f"No axis named {axis} for object type {self.__class__.__name__}"
)
if isinstance(self, Series) and axis == 1:
raise ValueError("No axis named 1 for object type Series")
is_lhs_dataframe_and_rhs_series = isinstance(self, pd.DataFrame) and isinstance(
other, pd.Series
)
is_lhs_series_and_rhs_dataframe = isinstance(self, pd.Series) and isinstance(
other, pd.DataFrame
)
if is_lhs_dataframe_and_rhs_series and axis is None:
raise ValueError("Must specify axis=0 or 1")
if (is_lhs_dataframe_and_rhs_series and axis == 1) or (
is_lhs_series_and_rhs_dataframe and axis is None
):
raise NotImplementedError(
f"The Snowpark pandas {self.__class__.__name__}.align with {other.__class__.__name__} other does not "
f"support axis={axis}."
)
query_compiler1, query_compiler2 = self._query_compiler.align(
other, join=join, axis=axis, level=level, copy=copy, fill_value=fill_value
)
if is_lhs_dataframe_and_rhs_series:
return DataFrame(query_compiler=query_compiler1), Series(
query_compiler=query_compiler2
)
elif is_lhs_series_and_rhs_dataframe:
return Series(query_compiler=query_compiler1), DataFrame(
query_compiler=query_compiler2
)
else:
return (
self._create_or_update_from_compiler(query_compiler1, False),
self._create_or_update_from_compiler(query_compiler2, False),
)
# Modin does not provide `MultiIndex` support and will default to pandas when `level` is specified,
# and allows binary ops against native pandas objects that Snowpark pandas prohibits.
@register_base_override("_binary_op")
def _binary_op(
self,
op: str,
other: BasePandasDataset,
axis: Axis = None,
level: Level | None = None,
fill_value: float | None = None,
**kwargs: Any,
):
"""
Do binary operation between two datasets.
Parameters
----------
op : str
Name of binary operation.
other : modin.pandas.BasePandasDataset
Second operand of binary operation.
axis: Whether to compare by the index (0 or ‘index’) or columns. (1 or ‘columns’).
level: Broadcast across a level, matching Index values on the passed MultiIndex level.
fill_value: Fill existing missing (NaN) values, and any new element needed for
successful DataFrame alignment, with this value before computation.
If data in both corresponding DataFrame locations is missing the result will be missing.
only arithmetic binary operation has this parameter (e.g., add() has, but eq() doesn't have).
kwargs can contain the following parameters passed in at the frontend:
func: Only used for `combine` method. Function that takes two series as inputs and
return a Series or a scalar. Used to merge the two dataframes column by columns.
Returns
-------
modin.pandas.BasePandasDataset
Result of binary operation.
"""
# In upstream modin, _axis indicates the operator will use the default axis
if kwargs.pop("_axis", None) is None:
if axis is not None:
axis = self._get_axis_number(axis)
else:
axis = 1
else:
axis = 0
# TODO: SNOW-1119855: Modin upgrade - modin.pandas.base.BasePandasDataset
raise_if_native_pandas_objects(other)
axis = self._get_axis_number(axis)
squeeze_self = isinstance(self, pd.Series)
# pandas itself will ignore the axis argument when using Series.<op>.
# Per default, it is set to axis=0. However, for the case of a Series interacting with
# a DataFrame the behavior is axis=1. Manually check here for this case and adjust the axis.
is_lhs_series_and_rhs_dataframe = (
True
if isinstance(self, pd.Series) and isinstance(other, pd.DataFrame)
else False
)
new_query_compiler = self._query_compiler.binary_op(
op=op,
other=other,
axis=1 if is_lhs_series_and_rhs_dataframe else axis,
level=level,
fill_value=fill_value,
squeeze_self=squeeze_self,
**kwargs,
)
from modin.pandas.dataframe import DataFrame
# Modin Bug: https://github.com/modin-project/modin/issues/7236
# For a Series interacting with a DataFrame, always return a DataFrame
return (
DataFrame(query_compiler=new_query_compiler)
if is_lhs_series_and_rhs_dataframe
else self._create_or_update_from_compiler(new_query_compiler)
)
# Current Modin does not use _dropna and instead defines `dropna` directly, but Snowpark pandas
# Series/DF still do. Snowpark pandas still needs to add support for the `ignore_index` parameter
# (added in pandas 2.0), and should be able to refactor to remove this override.
@register_base_override("_dropna")
def _dropna(
self,
axis: Axis = 0,
how: str | NoDefault = no_default,
thresh: int | NoDefault = no_default,
subset: IndexLabel = None,
inplace: bool = False,
):
inplace = validate_bool_kwarg(inplace, "inplace")
if is_list_like(axis):
raise TypeError("supplying multiple axes to axis is no longer supported.")
axis = self._get_axis_number(axis)
if (how is not no_default) and (thresh is not no_default):
raise TypeError(
"You cannot set both the how and thresh arguments at the same time."
)
if how is no_default:
how = "any"
if how not in ["any", "all"]:
raise ValueError("invalid how option: %s" % how)
if subset is not None:
if axis != 1:
indices = self.columns.get_indexer_for(
subset if is_list_like(subset) else [subset]
)
check = indices == -1
if check.any():
raise KeyError([k.item() for k in np.compress(check, subset)])
new_query_compiler = self._query_compiler.dropna(
axis=axis,
how=how,
thresh=thresh,
subset=subset,
)
return self._create_or_update_from_compiler(new_query_compiler, inplace)
# Snowpark pandas uses `self_is_series` instead of `squeeze_self` and `squeeze_value` to determine
# the shape of `self` and `value`. Further work is needed to reconcile these two approaches.
@register_base_override("fillna")
def fillna(
self,
self_is_series,
value: Hashable | Mapping | pd.Series | pd.DataFrame = None,
method: FillnaOptions | None = None,
axis: Axis | None = None,
inplace: bool = False,
limit: int | None = None,
downcast: dict | None = None,
):
"""
Fill NA/NaN values using the specified method.
Parameters
----------
self_is_series : bool
If True then self contains a Series object, if False then self contains
a DataFrame object.
value : scalar, dict, Series, or DataFrame, default: None
Value to use to fill holes (e.g. 0), alternately a
dict/Series/DataFrame of values specifying which value to use for
each index (for a Series) or column (for a DataFrame). Values not
in the dict/Series/DataFrame will not be filled. This value cannot
be a list.
method : {'backfill', 'bfill', 'pad', 'ffill', None}, default: None
Method to use for filling holes in reindexed Series
pad / ffill: propagate last valid observation forward to next valid
backfill / bfill: use next valid observation to fill gap.
axis : {None, 0, 1}, default: None
Axis along which to fill missing values.
inplace : bool, default: False
If True, fill in-place. Note: this will modify any
other views on this object (e.g., a no-copy slice for a column in a
DataFrame).
limit : int, default: None
If method is specified, this is the maximum number of consecutive