-
Notifications
You must be signed in to change notification settings - Fork 147
Expand file tree
/
Copy pathseries_overrides.py
More file actions
2261 lines (1907 loc) · 72.7 KB
/
series_overrides.py
File metadata and controls
2261 lines (1907 loc) · 72.7 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.
#
"""
File containing Series APIs defined in the Modin API layer, but with different behavior in Snowpark
pandas, such as `Series.memory_usage`.
"""
from __future__ import annotations
import copy
import functools
from typing import IO, Any, Callable, Hashable, Literal, Mapping, Sequence, get_args
import modin.pandas as pd
import numpy as np
import numpy.typing as npt
import pandas as native_pd
from modin.pandas import DataFrame, Series
from modin.pandas.base import (
BasePandasDataset,
_ATTRS_NO_LOOKUP,
sentinel,
)
from modin.core.storage_formats.pandas.query_compiler_caster import (
EXTENSION_NO_LOOKUP,
register_function_for_pre_op_switch,
)
from modin.pandas.io import from_pandas
from modin.pandas.utils import is_scalar
from pandas._libs.lib import NoDefault, is_integer, no_default
from pandas._typing import (
AggFuncType,
AnyArrayLike,
ArrayLike,
Axis,
FilePath,
FillnaOptions,
IgnoreRaise,
IndexKeyFunc,
IndexLabel,
Level,
NaPosition,
Renamer,
Scalar,
StorageOptions,
WriteExcelBuffer,
)
from pandas.core.common import apply_if_callable, is_bool_indexer
from pandas.core.dtypes.common import is_bool_dtype, is_dict_like, is_list_like
from pandas.util._validators import validate_ascending, validate_bool_kwarg
from snowflake.snowpark.modin.plugin._internal.utils import (
assert_fields_are_none,
convert_index_to_list_of_qcs,
convert_index_to_qc,
error_checking_for_init,
)
from snowflake.snowpark.modin.plugin.compiler.snowflake_query_compiler import (
HYBRID_SWITCH_FOR_UNIMPLEMENTED_METHODS,
)
from snowflake.snowpark.modin.plugin._typing import DropKeep, ListLike
from snowflake.snowpark.modin.plugin.extensions.snow_partition_iterator import (
SnowparkPandasRowPartitionIterator,
)
from snowflake.snowpark.modin.plugin.utils.error_message import (
ErrorMessage,
series_not_implemented,
)
from snowflake.snowpark.modin.plugin.utils.frontend_constants import (
SERIES_ITEMS_WARNING_MESSAGE,
SERIES_SETITEM_INCOMPATIBLE_INDEXER_WITH_SCALAR_ERROR_MESSAGE,
SERIES_SETITEM_INCOMPATIBLE_INDEXER_WITH_SERIES_ERROR_MESSAGE,
SERIES_SETITEM_LIST_LIKE_KEY_AND_RANGE_LIKE_VALUE_ERROR_MESSAGE,
SERIES_SETITEM_SLICE_AS_SCALAR_VALUE_ERROR_MESSAGE,
)
from snowflake.snowpark.modin.plugin.utils.warning_message import (
WarningMessage,
materialization_warning,
)
from snowflake.snowpark.modin.utils import (
MODIN_UNNAMED_SERIES_LABEL,
_inherit_docstrings,
validate_int_kwarg,
)
from modin.pandas.api.extensions import (
register_series_accessor as _register_series_accessor,
)
register_series_accessor = functools.partial(
_register_series_accessor, backend="Snowflake"
)
def register_series_not_implemented():
def decorator(base_method: Any):
func = series_not_implemented()(base_method)
name = (
base_method.fget.__name__
if isinstance(base_method, property)
else base_method.__name__
)
HYBRID_SWITCH_FOR_UNIMPLEMENTED_METHODS.add(("Series", name))
register_function_for_pre_op_switch(
class_name="Series", backend="Snowflake", method=name
)
register_series_accessor(name)(func)
return func
return decorator
# Upstream modin has an extra check for `key in self.index`, which produces an extra query
# when an attribute is not present.
# Because __getattr__ itself is responsible for resolving extension methods, we cannot override
# this method via the extensions module, and have to do it with an old-fashioned set.
# We cannot name this method __getattr__ because Python will treat this as this file's __getattr__.
def _getattr_impl(self, key):
"""
Return item identified by `key`.
Parameters
----------
key : hashable
Key to get.
Returns
-------
Any
Notes
-----
First try to use `__getattribute__` method. If it fails
try to get `key` from `Series` fields.
"""
# NOTE that to get an attribute, python calls __getattribute__() first and
# then falls back to __getattr__() if the former raises an AttributeError.
try:
if key not in EXTENSION_NO_LOOKUP:
extension = self._getattr__from_extension_impl(
key, set(), Series._extensions
)
if extension is not sentinel:
return extension
return super(Series, self).__getattr__(key)
except AttributeError as err:
if key not in _ATTRS_NO_LOOKUP:
try:
value = self[key]
if isinstance(value, Series) and value.empty:
raise err
return value
except Exception:
# We want to raise err if self[key] raises any kind of exception
raise err
raise err
Series.__getattr__ = _getattr_impl
# === 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_series_not_implemented()
def argsort(self, axis=0, kind="quicksort", order=None): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_series_not_implemented()
def transform(self, func, axis=0, *args, **kwargs): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_series_not_implemented()
def autocorr(self, lag=1): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_series_not_implemented()
def corr(self, other, method="pearson", min_periods=None): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_series_not_implemented()
def cov(self, other, min_periods=None, ddof: int | None = 1): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_series_not_implemented()
def divmod(self, other, level=None, fill_value=None, axis=0): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_series_not_implemented()
def dot(self, other): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_series_not_implemented()
def explode(self, ignore_index: bool = False): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_series_not_implemented()
def factorize(
self, sort=False, na_sentinel=no_default, use_na_sentinel=no_default
): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_series_accessor("hist")
def hist(
self,
by=None,
ax=None,
grid: bool = True,
xlabelsize: int | None = None,
xrot: float | None = None,
ylabelsize: int | None = None,
yrot: float | None = None,
figsize: tuple[int, int] | None = None,
bins: int | Sequence[int] = 10,
backend: str | None = None,
legend: bool = False,
**kwargs,
): # noqa: PR01, RT01, D200
if bins is None:
bins = 10
# Get the query compiler representing the histogram data to be plotted.
# Along with the query compiler, also get the minimum and maximum values in the input series, and the computed bin size.
(
new_query_compiler,
min_val,
max_val,
bin_size,
) = self._query_compiler.hist_on_series(
by=by,
xlabelsize=xlabelsize,
xrot=xrot,
ylabelsize=ylabelsize,
yrot=yrot,
figsize=figsize,
bins=bins,
backend=backend,
legend=legend,
**kwargs,
)
# Convert the result to native pandas in preparation for plotting it using Matplotlib's bar chart.
# Note that before converting to native pandas, the data had already been reduced in the previous step.
native_ser = self.__constructor__(query_compiler=new_query_compiler)._to_pandas()
# Ensure that we have enough rows in the series corresponding to all bins, even if some of them are empty.
native_ser_reindexed = native_ser.reindex(
native_pd.Index(np.linspace(min_val, max_val, bins + 1)),
method="nearest",
tolerance=bin_size / 3,
).fillna(0)
# Prepare the visualization parameters to be used for rendering the bar chart.
import matplotlib.pyplot as plt
fig = kwargs.pop(
"figure", plt.gcf() if plt.get_fignums() else plt.figure(figsize=figsize)
)
if ax is None:
ax = fig.gca()
ax.grid(grid)
counts = native_ser_reindexed.to_list()[0:-1]
vals = native_ser_reindexed.index.to_list()[0:-1]
bar_labels = vals
ax.bar(vals, counts, label=bar_labels, width=bin_size, align="edge")
return ax
@register_series_not_implemented()
def item(self): # noqa: RT01, D200
pass # pragma: no cover
# Snowpark pandas has a custom iterator.
@register_series_accessor("items")
def items(self):
# TODO: SNOW-1063347: Modin upgrade - modin.pandas.Series functions
"""
Iterate over ``Series`` rows as (index, value) tuples.
"""
def items_builder(s):
"""Return tuple of the given ``Series`` in the form (index, value)."""
return s.name, s.squeeze()
# Raise warning message since Series.items is very inefficient.
WarningMessage.single_warning(SERIES_ITEMS_WARNING_MESSAGE)
return SnowparkPandasRowPartitionIterator(DataFrame(self), items_builder, True)
@register_series_not_implemented()
def mode(self, dropna=True): # noqa: PR01, RT01, D200
pass
@register_series_not_implemented()
def prod(
self,
axis=None,
skipna=True,
level=None,
numeric_only=False,
min_count=0,
**kwargs,
):
pass # pragma: no cover
@register_series_not_implemented()
def ravel(self, order="C"): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_series_not_implemented()
def rdivmod(self, other, level=None, fill_value=None, axis=0): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_series_not_implemented()
def reindex_like(
self,
other,
method=None,
copy: bool | None = None,
limit=None,
tolerance=None,
) -> Series:
pass # pragma: no cover
@register_series_not_implemented()
def reorder_levels(self, order): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_series_not_implemented()
def repeat(self, repeats, axis=None): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_series_not_implemented()
def searchsorted(self, value, side="left", sorter=None): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_series_not_implemented()
def swaplevel(self, i=-2, j=-1, copy=True): # noqa: PR01, RT01, D200
pass # pragma: no cover
def to_excel(
self,
excel_writer: FilePath | WriteExcelBuffer | pd.ExcelWriter,
sheet_name: str = "Sheet1",
na_rep: str = "",
float_format: str | None = None,
columns: Sequence[Hashable] | None = None,
header: Sequence[Hashable] | bool = True,
index: bool = True,
index_label: IndexLabel | None = None,
startrow: int = 0,
startcol: int = 0,
engine: Literal["openpyxl", "xlsxwriter"] | None = None,
merge_cells: bool = True,
inf_rep: str = "inf",
freeze_panes: tuple[int, int] | None = None,
storage_options: StorageOptions | None = None,
engine_kwargs: dict[str, Any] | None = None,
): # noqa: PR01, RT01, D200
WarningMessage.single_warning(
"Series.to_excel materializes data to the local machine."
)
return self._to_pandas().to_excel(
excel_writer=excel_writer,
sheet_name=sheet_name,
na_rep=na_rep,
float_format=float_format,
columns=columns,
header=header,
index=index,
index_label=index_label,
startrow=startrow,
startcol=startcol,
engine=engine,
merge_cells=merge_cells,
inf_rep=inf_rep,
freeze_panes=freeze_panes,
storage_options=storage_options,
engine_kwargs=engine_kwargs,
)
@register_series_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=None,
indent=None,
storage_options: StorageOptions = None,
mode="w",
) -> str | None: # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_series_not_implemented()
def to_period(self, freq=None, copy=True): # noqa: PR01, RT01, D200
pass # pragma: no cover
def to_string(
self,
buf=None,
na_rep="NaN",
float_format=None,
header=True,
index=True,
length=False,
dtype=False,
name=False,
max_rows=None,
min_rows=None,
): # noqa: PR01, RT01, D200
WarningMessage.single_warning(
"Series.to_string materializes data to the local machine."
)
return self._to_pandas().to_string(
buf=buf,
na_rep=na_rep,
float_format=float_format,
header=header,
index=index,
length=length,
dtype=dtype,
name=name,
max_rows=max_rows,
min_rows=min_rows,
)
@register_series_not_implemented()
def to_timestamp(self, freq=None, how="start", copy=True): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_series_not_implemented()
def update(self, other) -> None: # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_series_not_implemented()
def view(self, dtype=None): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_series_not_implemented()
@property
def array(self): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_series_not_implemented()
@property
def nbytes(self): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_series_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_series_not_implemented()
def __reduce__(self): # noqa: PR01, RT01, D200
pass # pragma: no cover
# === OVERRIDDEN METHODS ===
# The below methods have their frontend implementations overridden compared to the version present
# in series.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
# Snowpark pandas overrides the constructor for two reasons:
# 1. To support the Snowpark pandas lazy index object
# 2. To avoid raising "UserWarning: Distributing <class 'list'> object. This may take some time."
# when a literal is passed in as data.
@register_series_accessor("__init__")
def __init__(
self,
data=None,
index=None,
dtype=None,
name=None,
copy=False,
fastpath=False,
query_compiler=None,
) -> None:
# TODO: SNOW-1063347: Modin upgrade - modin.pandas.Series functions
# Siblings are other dataframes that share the same query compiler. We
# use this list to update inplace when there is a shallow copy.
self._siblings = []
from snowflake.snowpark.modin.plugin.extensions.index import Index
# Setting the query compiler
# --------------------------
if query_compiler is not None:
# If a query_compiler is passed in, only use the query_compiler and name fields to create a new Series.
# Verify that the data and index parameters are None.
assert_fields_are_none(class_name="Series", data=data, index=index, dtype=dtype)
self._query_compiler = query_compiler.columnarize()
if name is not None:
self.name = name
return
# A DataFrame cannot be used as an index and Snowpark pandas does not support the Categorical type yet.
# Check that index is not a DataFrame and dtype is not "category".
error_checking_for_init(index, dtype)
if isinstance(data, pd.DataFrame):
# data cannot be a DataFrame, raise a clear error message.
# pandas raises an ambiguous error:
# ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
raise ValueError("Data cannot be a DataFrame")
# The logic followed here is:
# STEP 1: Create a query_compiler from the provided data.
# STEP 2: If an index is provided, set the index. This is either through set_index or reindex.
# STEP 3: If a dtype is given, and it is different from the current dtype of the query compiler so far,
# convert the query compiler to the given dtype if the data is lazy.
# STEP 4: The resultant query_compiler is columnarized and set as the query_compiler for the Series.
# STEP 5: If a name is provided, set the name.
# STEP 1: Setting the data
# ------------------------
if isinstance(data, Index):
# If the data is an Index object, convert it to a Series, and get the query_compiler.
query_compiler = (
data.to_series(index=None, name=name).reset_index(drop=True)._query_compiler
)
elif isinstance(data, Series):
# If the data is a Series object, use its query_compiler.
query_compiler = data._query_compiler
if (
copy is False
and index is None
and name is None
and (dtype is None or dtype == getattr(data, "dtype", None))
):
# When copy is False and no index, name, and dtype are provided, the Series is a shallow copy of the
# original Series.
# If a dtype is provided, and the new dtype does not match the dtype of the original query compiler,
# self is no longer a sibling of the original DataFrame.
self._query_compiler = query_compiler
data._add_sibling(self)
return
else:
# If the data is not a Snowpark pandas object, convert it to a query compiler.
# The query compiler uses the '__reduced__' name internally as a column name to represent pandas
# Series objects that are not explicitly assigned a name.
# This helps to distinguish between an N-element Series and 1xN DataFrame.
name = name or MODIN_UNNAMED_SERIES_LABEL
if hasattr(data, "name") and data.name is not None:
# If data is an object that has a name field, use that as the name of the new Series.
name = data.name
# If any of the values are Snowpark pandas objects, convert them to native pandas objects.
if not isinstance(
data, (native_pd.DataFrame, native_pd.Series, native_pd.Index)
) and is_list_like(data):
if is_dict_like(data):
data = {
k: v.to_list() if isinstance(v, (Index, BasePandasDataset)) else v
for k, v in data.items()
}
else:
data = [
v.to_list() if isinstance(v, (Index, BasePandasDataset)) else v
for v in data
]
query_compiler = from_pandas(
native_pd.DataFrame(
native_pd.Series(
data=data,
# If the index is a lazy index, handle setting it outside this block.
index=None if isinstance(index, (Index, Series)) else index,
dtype=dtype,
name=name,
copy=copy,
fastpath=fastpath,
)
)
)._query_compiler
# STEP 2: Setting the index
# -------------------------
# The index is already set if the data is a non-Snowpark pandas object.
# If either the data or the index is a Snowpark pandas object, set the index here.
if index is not None and (
isinstance(index, (Index, type(self))) or isinstance(data, (Index, type(self)))
):
if is_dict_like(data) or isinstance(data, (type(self), type(None))):
# The `index` parameter is used to select the rows from `data` that will be in the resultant Series.
# If a value in `index` is not present in `data`'s index, it will be filled with a NaN value.
# If data is None and an index is provided, all the values in the Series will be NaN and the index
# will be the provided index.
query_compiler = query_compiler.reindex(
axis=0, labels=convert_index_to_qc(index)
)
else:
# Performing set index to directly set the index column (joining on row-position instead of index).
query_compiler = query_compiler.set_index(
convert_index_to_list_of_qcs(index)
)
# STEP 3: Setting the dtype if data is lazy
# -----------------------------------------
# If data is a Snowpark pandas object and a dtype is provided, and it does not match the current dtype of the
# query compiler, convert the query compiler's dtype to the new dtype.
# Local data should have the dtype parameter taken care of by the pandas constructor at the end.
if (
dtype is not None
and isinstance(data, (Index, Series))
and dtype != getattr(data, "dtype", None)
):
query_compiler = query_compiler.astype(
{col: dtype for col in query_compiler.columns}
)
# STEP 4 and STEP 5: Setting the query compiler and name
# ------------------------------------------------------
self._query_compiler = query_compiler.columnarize()
if name is not None:
self.name = name
def _update_inplace(self, new_query_compiler) -> None:
"""
Update the current Series in-place using `new_query_compiler`.
Parameters
----------
new_query_compiler : BaseQueryCompiler
QueryCompiler to use to manage the data.
"""
super(Series, self)._update_inplace(new_query_compiler=new_query_compiler)
# Propagate changes back to parent so that column in dataframe had the same contents
if self._parent is not None:
if self._parent_axis == 1 and isinstance(self._parent, DataFrame):
self._parent[self.name] = self
else:
self._parent.loc[self.index] = self
# Modin uses _update_inplace to implement set_backend(inplace=True), so in modin 0.33 and newer we
# can't extend _update_inplace. To fix a query count bug specific to Snowflake in _update_inplace, we overwrite
# _update_inplace entirely instead of using the extension system.
Series._update_inplace = _update_inplace
# Since Snowpark pandas leaves all data on the warehouse, memory_usage's report of local memory
# usage isn't meaningful and is set to always return 0.
@_inherit_docstrings(native_pd.Series.memory_usage, apilink="pandas.Series")
@register_series_accessor("memory_usage")
def memory_usage(self, index: bool = True, deep: bool = False) -> int:
"""
Return zero bytes for memory_usage
"""
# TODO: SNOW-1264697: push implementation down to query compiler
return 0
# Snowpark pandas has slightly different type validation from upstream modin.
@_inherit_docstrings(native_pd.Series.isin, apilink="pandas.Series")
@register_series_accessor("isin")
def isin(self, values: set | ListLike) -> Series:
"""
Whether elements in Series are contained in `values`.
Return a boolean Series showing whether each element in the Series
matches an element in the passed sequence of `values`.
Caution
-------
Snowpark pandas deviates from pandas here with respect to NA values: when the value is considered NA or
values contains at least one NA, None is returned instead of a boolean value.
Parameters
----------
values : set or list-like
The sequence of values to test. Passing in a single string will
raise a ``TypeError``. Instead, turn a single string into a
list of one element.
Returns
-------
Series
Series of booleans indicating if each element is in values.
Examples
--------
>>> s = pd.Series(['lama', 'cow', 'lama', 'beetle', 'lama',
... 'hippo'], name='animal')
>>> s.isin(['cow', 'lama'])
0 True
1 True
2 True
3 False
4 True
5 False
Name: animal, dtype: bool
To invert the boolean values, use the ``~`` operator:
>>> ~s.isin(['cow', 'lama'])
0 False
1 False
2 False
3 True
4 False
5 True
Name: animal, dtype: bool
Passing a single string as ``s.isin('lama')`` will raise an error. Use
a list of one element instead:
>>> s.isin(['lama'])
0 True
1 False
2 True
3 False
4 True
5 False
Name: animal, dtype: bool
>>> pd.Series([1]).isin(['1'])
0 False
dtype: bool
>>> pd.Series([1, 2, None]).isin([2])
0 False
1 True
2 None
dtype: object
"""
# pandas compatible TypeError
if isinstance(values, str):
raise TypeError(
"only list-like objects are allowed to be passed to isin(), you passed a [str]"
)
# convert to list if given as set
if isinstance(values, set):
values = list(values)
return super(Series, self).isin(values, self_is_series=True)
# Snowpark pandas raises a warning before materializing data and passing to `plot`.
@register_series_accessor("plot")
@property
def plot(
self,
kind="line",
ax=None,
figsize=None,
use_index=True,
title=None,
grid=None,
legend=False,
style=None,
logx=False,
logy=False,
loglog=False,
xticks=None,
yticks=None,
xlim=None,
ylim=None,
rot=None,
fontsize=None,
colormap=None,
table=False,
yerr=None,
xerr=None,
label=None,
secondary_y=False,
**kwds,
): # noqa: PR01, RT01, D200
"""
Make plot of Series.
"""
# TODO: SNOW-1063347: Modin upgrade - modin.pandas.Series functions
WarningMessage.single_warning(
"Series.plot materializes data to the local machine for plotting."
)
return self._to_pandas().plot
# Upstream Modin has a bug binary operators (except add/radd, ) don't respect fill_value:
# https://github.com/modin-project/modin/issues/7381
@register_series_accessor("sub")
def sub(self, other, level=None, fill_value=None, axis=0): # noqa: PR01, RT01, D200
"""
Return subtraction of Series and `other`, element-wise (binary operator `sub`).
"""
# TODO: SNOW-1063347: Modin upgrade - modin.pandas.Series functions
return super(Series, self).sub(other, level=level, fill_value=fill_value, axis=axis)
register_series_accessor("subtract")(sub)
@register_series_accessor("rsub")
def rsub(self, other, level=None, fill_value=None, axis=0): # noqa: PR01, RT01, D200
"""
Return subtraction of series and `other`, element-wise (binary operator `rsub`).
"""
# TODO: SNOW-1063347: Modin upgrade - modin.pandas.Series functions
return super(Series, self).rsub(
other, level=level, fill_value=fill_value, axis=axis
)
@register_series_accessor("mul")
def mul(self, other, level=None, fill_value=None, axis=0): # noqa: PR01, RT01, D200
"""
Return multiplication of series and `other`, element-wise (binary operator `mul`).
"""
# TODO: SNOW-1063347: Modin upgrade - modin.pandas.Series functions
return super(Series, self).mul(other, level=level, fill_value=fill_value, axis=axis)
register_series_accessor("multiply")(mul)
@register_series_accessor("rmul")
def rmul(self, other, level=None, fill_value=None, axis=0): # noqa: PR01, RT01, D200
"""
Return multiplication of series and `other`, element-wise (binary operator `mul`).
"""
# TODO: SNOW-1063347: Modin upgrade - modin.pandas.Series functions
return super(Series, self).rmul(
other, level=level, fill_value=fill_value, axis=axis
)
@register_series_accessor("truediv")
def truediv(self, other, level=None, fill_value=None, axis=0): # noqa: PR01, RT01, D200
"""
Return floating division of series and `other`, element-wise (binary operator `truediv`).
"""
# TODO: SNOW-1063347: Modin upgrade - modin.pandas.Series functions
return super(Series, self).truediv(
other, level=level, fill_value=fill_value, axis=axis
)
register_series_accessor("div")(truediv)
register_series_accessor("divide")(truediv)
@register_series_accessor("rtruediv")
def rtruediv(
self, other, level=None, fill_value=None, axis=0
): # noqa: PR01, RT01, D200
"""
Return floating division of series and `other`, element-wise (binary operator `rtruediv`).
"""
# TODO: SNOW-1063347: Modin upgrade - modin.pandas.Series functions
return super(Series, self).rtruediv(
other, level=level, fill_value=fill_value, axis=axis
)
register_series_accessor("rdiv")(rtruediv)
@register_series_accessor("floordiv")
def floordiv(
self, other, level=None, fill_value=None, axis=0
): # noqa: PR01, RT01, D200
"""
Get Integer division of dataframe and `other`, element-wise (binary operator `floordiv`).
"""
# TODO: SNOW-1063347: Modin upgrade - modin.pandas.Series functions
return super(Series, self).floordiv(
other, level=level, fill_value=fill_value, axis=axis
)
@register_series_accessor("rfloordiv")
def rfloordiv(
self, other, level=None, fill_value=None, axis=0
): # noqa: PR01, RT01, D200
"""
Return integer division of series and `other`, element-wise (binary operator `rfloordiv`).
"""
# TODO: SNOW-1063347: Modin upgrade - modin.pandas.Series functions
return super(Series, self).rfloordiv(
other, level=level, fill_value=fill_value, axis=axis
)
@register_series_accessor("mod")
def mod(self, other, level=None, fill_value=None, axis=0): # noqa: PR01, RT01, D200
"""
Return Modulo of series and `other`, element-wise (binary operator `mod`).
"""
# TODO: SNOW-1063347: Modin upgrade - modin.pandas.Series functions
return super(Series, self).mod(other, level=level, fill_value=fill_value, axis=axis)
@register_series_accessor("rmod")
def rmod(self, other, level=None, fill_value=None, axis=0): # noqa: PR01, RT01, D200
"""
Return modulo of series and `other`, element-wise (binary operator `rmod`).
"""
# TODO: SNOW-1063347: Modin upgrade - modin.pandas.Series functions
return super(Series, self).rmod(
other, level=level, fill_value=fill_value, axis=axis
)
@register_series_accessor("pow")
def pow(self, other, level=None, fill_value=None, axis=0): # noqa: PR01, RT01, D200
"""
Return exponential power of series and `other`, element-wise (binary operator `pow`).
"""
# TODO: SNOW-1063347: Modin upgrade - modin.pandas.Series functions
return super(Series, self).pow(other, level=level, fill_value=fill_value, axis=axis)
@register_series_accessor("rpow")
def rpow(self, other, level=None, fill_value=None, axis=0): # noqa: PR01, RT01, D200
"""
Return exponential power of series and `other`, element-wise (binary operator `rpow`).
"""
# TODO: SNOW-1063347: Modin upgrade - modin.pandas.Series functions
return super(Series, self).rpow(
other, level=level, fill_value=fill_value, axis=axis
)
# Modin defaults to pandas for binary operators against native pandas/list objects.
@register_series_accessor("__add__")
def __add__(self, right):
# TODO: SNOW-1063347: Modin upgrade - modin.pandas.Series functions
return self.add(right)
# Modin defaults to pandas for binary operators against native pandas/list objects.
@register_series_accessor("__radd__")
def __radd__(self, left):
# TODO: SNOW-1063347: Modin upgrade - modin.pandas.Series functions
return self.radd(left)
# Modin defaults to pandas for binary operators against native pandas/list objects.
@register_series_accessor("__and__")