-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathdataframe_overrides.py
More file actions
2526 lines (2216 loc) · 85.8 KB
/
dataframe_overrides.py
File metadata and controls
2526 lines (2216 loc) · 85.8 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 DataFrame APIs defined in the Modin API layer, but with different behavior in Snowpark
pandas, such as `DataFrame.memory_usage`.
"""
from __future__ import annotations
import collections
import datetime
import functools
import itertools
import sys
import warnings
from typing import (
IO,
Any,
Callable,
Hashable,
Iterable,
Iterator,
Literal,
Mapping,
Sequence,
)
import modin.pandas as pd
import numpy as np
import pandas as native_pd
from modin.pandas import DataFrame, Series
from pandas.core.interchange.dataframe_protocol import DataFrame as InterchangeDataframe
from modin.pandas.api.extensions import register_dataframe_accessor
from modin.pandas.base import BasePandasDataset
from modin.pandas.io import from_pandas
from modin.pandas.utils import is_scalar
from pandas._libs.lib import NoDefault, no_default
from pandas._typing import (
AggFuncType,
AnyArrayLike,
Axes,
Axis,
CompressionOptions,
FilePath,
FillnaOptions,
IgnoreRaise,
IndexLabel,
Level,
PythonFuncType,
Renamer,
Scalar,
StorageOptions,
Suffixes,
WriteBuffer,
)
from pandas.core.common import apply_if_callable, is_bool_indexer
from pandas.core.dtypes.common import (
infer_dtype_from_object,
is_bool_dtype,
is_dict_like,
is_list_like,
is_numeric_dtype,
)
from pandas.core.dtypes.inference import is_hashable, is_integer
from pandas.core.indexes.base import ensure_index as ensure_native_index
from pandas.core.indexes.frozen import FrozenList
from pandas.io.formats.printing import pprint_thing
from pandas.util._validators import validate_bool_kwarg
from snowflake.snowpark.modin.plugin._internal.aggregation_utils import (
is_snowflake_agg_func,
)
from snowflake.snowpark.modin.plugin._internal.utils import (
add_extra_columns_and_select_required_columns,
assert_fields_are_none,
convert_index_to_list_of_qcs,
convert_index_to_qc,
error_checking_for_init,
is_repr_truncated,
)
from snowflake.snowpark.modin.plugin._typing import ListLike
from snowflake.snowpark.modin.plugin.compiler.snowflake_query_compiler import (
SnowflakeQueryCompiler,
)
from snowflake.snowpark.modin.plugin.extensions.groupby_overrides import (
DataFrameGroupBy,
validate_groupby_args,
)
from snowflake.snowpark.modin.plugin.extensions.index import Index
from snowflake.snowpark.modin.plugin.extensions.snow_partition_iterator import (
SnowparkPandasRowPartitionIterator,
)
from snowflake.snowpark.modin.plugin.extensions.utils import (
create_empty_native_pandas_frame,
raise_if_native_pandas_objects,
replace_external_data_keys_with_empty_pandas_series,
replace_external_data_keys_with_query_compiler,
try_convert_index_to_native,
)
from snowflake.snowpark.modin.plugin.utils.error_message import (
ErrorMessage,
dataframe_not_implemented,
)
from snowflake.snowpark.modin.plugin.utils.frontend_constants import (
DF_ITERROWS_ITERTUPLES_WARNING_MESSAGE,
DF_SETITEM_LIST_LIKE_KEY_AND_RANGE_LIKE_VALUE,
DF_SETITEM_SLICE_AS_SCALAR_VALUE,
)
from snowflake.snowpark.modin.plugin.utils.warning_message import WarningMessage
from snowflake.snowpark.modin.utils import (
_inherit_docstrings,
hashable,
validate_int_kwarg,
)
from snowflake.snowpark.udf import UserDefinedFunction
def register_dataframe_not_implemented():
def decorator(base_method: Any):
func = dataframe_not_implemented()(base_method)
register_dataframe_accessor(base_method.__name__)(func)
return func
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.
# Avoid overwriting builtin `map` by accident
@register_dataframe_accessor("map")
def _map(self, func: PythonFuncType, na_action: str | None = None, **kwargs):
# TODO: SNOW-1063346: Modin upgrade - modin.pandas.DataFrame functions
if not callable(func):
raise TypeError(f"{func} is not callable") # pragma: no cover
return self.__constructor__(
query_compiler=self._query_compiler.applymap(
func, na_action=na_action, **kwargs
)
)
@register_dataframe_not_implemented()
def boxplot(
self,
column=None,
by=None,
ax=None,
fontsize=None,
rot=0,
grid=True,
figsize=None,
layout=None,
return_type=None,
backend=None,
**kwargs,
): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_dataframe_not_implemented()
def combine(
self, other, func, fill_value=None, overwrite=True
): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_dataframe_not_implemented()
def corrwith(
self, other, axis=0, drop=False, method="pearson", numeric_only=False
): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_dataframe_not_implemented()
def cov(
self, min_periods=None, ddof: int | None = 1, numeric_only=False
): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_dataframe_not_implemented()
def dot(self, other): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_dataframe_not_implemented()
def eval(self, expr, inplace=False, **kwargs): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_dataframe_not_implemented()
def hist(
self,
column=None,
by=None,
grid=True,
xlabelsize=None,
xrot=None,
ylabelsize=None,
yrot=None,
ax=None,
sharex=False,
sharey=False,
figsize=None,
layout=None,
bins=10,
**kwds,
):
pass # pragma: no cover
@register_dataframe_not_implemented()
def isetitem(self, loc, value):
pass # pragma: no cover
@register_dataframe_not_implemented()
def prod(
self,
axis=None,
skipna=True,
numeric_only=False,
min_count=0,
**kwargs,
): # noqa: PR01, RT01, D200
pass # pragma: no cover
register_dataframe_accessor("product")(prod)
@register_dataframe_not_implemented()
def query(self, expr, inplace=False, **kwargs): # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_dataframe_not_implemented()
def reindex_like(
self,
other,
method=None,
copy: bool | None = None,
limit=None,
tolerance=None,
) -> DataFrame: # pragma: no cover
pass # pragma: no cover
@register_dataframe_not_implemented()
def to_feather(self, path, **kwargs): # pragma: no cover # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_dataframe_not_implemented()
def to_gbq(
self,
destination_table,
project_id=None,
chunksize=None,
reauth=False,
if_exists="fail",
auth_local_webserver=True,
table_schema=None,
location=None,
progress_bar=True,
credentials=None,
): # pragma: no cover # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_dataframe_not_implemented()
def to_orc(self, path=None, *, engine="pyarrow", index=None, engine_kwargs=None):
pass # pragma: no cover
def to_html(
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,
justify=None,
max_rows=None,
max_cols=None,
show_dimensions=False,
decimal=".",
bold_rows=True,
classes=None,
escape=True,
notebook=False,
border=None,
table_id=None,
render_links=False,
encoding=None,
): # noqa: PR01, RT01, D200
WarningMessage.single_warning(
"DataFrame.to_html materializes data to the local machine."
)
return self._to_pandas().to_html
@register_dataframe_not_implemented()
def to_parquet(
self,
path=None,
engine="auto",
compression="snappy",
index=None,
partition_cols=None,
storage_options: StorageOptions = None,
**kwargs,
):
pass # pragma: no cover
@register_dataframe_not_implemented()
def to_period(
self, freq=None, axis=0, copy=True
): # pragma: no cover # noqa: PR01, RT01, D200
pass # pragma: no cover
@register_dataframe_not_implemented()
def to_records(
self, index=True, column_dtypes=None, index_dtypes=None
): # noqa: PR01, RT01, D200
pass # pragma: no cover
def to_string(
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,
justify=None,
max_rows=None,
min_rows=None,
max_cols=None,
show_dimensions=False,
decimal=".",
line_width=None,
max_colwidth=None,
encoding=None,
): # noqa: PR01, RT01, D200
WarningMessage.single_warning(
"DataFrame.to_string materializes data to the local machine."
)
return self._to_pandas().to_string(
buf=buf,
columns=columns,
col_space=col_space,
header=header,
index=index,
na_rep=na_rep,
formatters=formatters,
float_format=float_format,
sparsify=sparsify,
index_names=index_names,
justify=justify,
max_rows=max_rows,
min_rows=min_rows,
max_cols=max_cols,
show_dimensions=show_dimensions,
decimal=decimal,
line_width=line_width,
max_colwidth=max_colwidth,
encoding=encoding,
)
@register_dataframe_not_implemented()
def to_stata(
self,
path: FilePath | WriteBuffer[bytes],
convert_dates: dict[Hashable, str] | None = None,
write_index: bool = True,
byteorder: str | None = None,
time_stamp: datetime.datetime | None = None,
data_label: str | None = None,
variable_labels: dict[Hashable, str] | None = None,
version: int | None = 114,
convert_strl: Sequence[Hashable] | None = None,
compression: CompressionOptions = "infer",
storage_options: StorageOptions = None,
*,
value_labels: dict[Hashable, dict[float | int, str]] | None = None,
):
pass # pragma: no cover
@register_dataframe_not_implemented()
def to_xml(
self,
path_or_buffer=None,
index=True,
root_name="data",
row_name="row",
na_rep=None,
attr_cols=None,
elem_cols=None,
namespaces=None,
prefix=None,
encoding="utf-8",
xml_declaration=True,
pretty_print=True,
parser="lxml",
stylesheet=None,
compression="infer",
storage_options=None,
):
pass # pragma: no cover
@register_dataframe_accessor("style")
@property
def style(self): # noqa: RT01, D200
return self._to_pandas().style
@register_dataframe_not_implemented()
def __reduce__(self):
pass # pragma: no cover
@register_dataframe_not_implemented()
def __divmod__(self, other):
pass # pragma: no cover
@register_dataframe_not_implemented()
def __rdivmod__(self, other):
pass # pragma: no cover
# The from_dict and from_records accessors are class methods and cannot be overridden via the
# extensions module, as they need to be foisted onto the namespace directly because they are not
# routed through getattr. To this end, we manually set DataFrame.from_dict to our new method.
@classmethod
def from_dict(
cls, data, orient="columns", dtype=None, columns=None
): # pragma: no cover # noqa: PR01, RT01, D200
"""
Construct ``DataFrame`` from dict of array-like or dicts.
"""
return DataFrame(
native_pd.DataFrame.from_dict(
data=data,
orient=orient,
dtype=dtype,
columns=columns,
)
)
DataFrame.from_dict = from_dict
@classmethod
def from_records(
cls,
data,
index=None,
exclude=None,
columns=None,
coerce_float=False,
nrows=None,
): # pragma: no cover # noqa: PR01, RT01, D200
"""
Convert structured or record ndarray to ``DataFrame``.
"""
if isinstance(data, DataFrame):
ErrorMessage.not_implemented(
"Snowpark pandas 'DataFrame.from_records' method does not yet support 'data' parameter of type 'DataFrame'"
)
return DataFrame(
native_pd.DataFrame.from_records(
data=data,
index=index,
exclude=exclude,
columns=columns,
coerce_float=coerce_float,
nrows=nrows,
)
)
DataFrame.from_records = from_records
# === 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_dataframe_accessor("__init__")
def __init__(
self,
data=None,
index=None,
columns=None,
dtype=None,
copy=None,
query_compiler=None,
) -> None:
# TODO: SNOW-1063346: Modin upgrade - modin.pandas.DataFrame 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 = []
# Setting the query compiler
# --------------------------
if query_compiler is not None:
# If a query_compiler is passed in only use the query_compiler field to create a new DataFrame.
# Verify that the data, index, and columns parameters are None.
assert_fields_are_none(
class_name="DataFrame", data=data, index=index, dtype=dtype, columns=columns
)
self._query_compiler = query_compiler
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)
# Convert columns to a local object if it is lazy.
if columns is not None:
columns = (
columns.to_pandas()
if isinstance(columns, (Index, BasePandasDataset))
else columns
)
columns = ensure_native_index(columns)
# The logic followed here is:
# STEP 1: Obtain the query_compiler from the provided data if the data is lazy. If data is local, keep the query
# compiler as None.
# STEP 2: If columns are provided, set the columns if the data is lazy.
# STEP 3: If both the data and index are local (or index is None), create a query compiler from it with local index.
# STEP 4: Otherwise, for lazy index, set the index through set_index or reindex.
# STEP 5: 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 6: The resultant query_compiler is then set as the query_compiler for the DataFrame.
# STEP 1: Setting the data
# ------------------------
if isinstance(data, Index):
# If the data is an Index object, convert it to a DataFrame to make sure that the values are in the
# correct format: the values should be a data column, not an index column.
# Converting the Index object to its DataFrame version sets the resultant DataFrame's column name correctly -
# it should be 0 if the name is None.
query_compiler = data.to_frame(index=False)._query_compiler
elif isinstance(data, Series):
# Rename the Series object to 0 if its name is None and grab its query compiler.
query_compiler = data.rename(
0 if data.name is None else data.name, inplace=False
)._query_compiler
elif isinstance(data, DataFrame):
query_compiler = data._query_compiler
if (
copy is False
and index is None
and columns is None
and (dtype is None or dtype == getattr(data, "dtype", None))
):
# When copy is False and no index, columns, and dtype are provided, the DataFrame is a shallow copy of the
# original DataFrame.
# 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
# STEP 2: Setting the columns if data is lazy
# -------------------------------------------
# When data is lazy, the query compiler is not None.
if query_compiler is not None:
if columns is not None:
if (
isinstance(data, (Index, Series))
and query_compiler.get_columns()[0] not in columns
):
# If the name of the Series/Index is not in the columns, clear the DataFrame and set the columns.
query_compiler = from_pandas(
native_pd.DataFrame(columns=columns)
)._query_compiler
else:
# Treat any columns not in data.columns (or data.name if data is a Series/Index) as extra columns.
# They will be appended as NaN columns. Then, select the required columns in the order provided by `columns`.
query_compiler = add_extra_columns_and_select_required_columns(
query_compiler, columns
)
# STEP 3: Creating a query compiler from pandas
# ---------------------------------------------
else: # When the data is local, the query compiler is None.
# If the data, columns, and index are local objects, the query compiler representation is created from pandas.
# However, when the data is a dict but the index is lazy, the index is converted to pandas and the query
# compiler is created from pandas.
if not isinstance(
data, (native_pd.Series, native_pd.DataFrame, native_pd.Index)
) and is_list_like(data):
# If data is a pandas object, directly handle it with the pandas constructor.
if is_dict_like(data):
if columns is not None:
# Reduce the dictionary to only the relevant columns as the keys.
data = {key: value for key, value in data.items() if key in columns}
if len(data) and all(
isinstance(v, (Index, BasePandasDataset)) for v in data.values()
):
# Special case: data is a dict where all the values are Snowpark pandas objects.
self._query_compiler = (
_df_init_dict_data_with_snowpark_pandas_values(
data, index, columns, dtype
)
)
return
# If only some data is a Snowpark pandas object, convert the lazy data to pandas objects.
res = {}
for k, v in data.items():
if isinstance(v, Index):
res[k] = v.to_pandas()
elif isinstance(v, BasePandasDataset):
# Need to perform reindex on the Series or DataFrame objects since only the data
# whose index matches the given index is kept.
res[k] = v.reindex(index=index).to_pandas()
else:
res[k] = v
# If the index is lazy, convert it to a pandas object so that the pandas constructor can handle it.
index = try_convert_index_to_native(index)
data = res
else: # list-like but not dict-like data.
if len(data) and all(
isinstance(v, (Index, BasePandasDataset)) for v in data
):
# Special case: data is a list/dict where all the values are Snowpark pandas objects.
self._query_compiler = (
_df_init_list_data_with_snowpark_pandas_values(
data, index, columns, dtype
)
)
return
# Sometimes the ndarray representation of a list is different from a regular list.
# For instance, [(1, 2, 3), (4, 5, 6), (7, 8, 9)], dtype=[("a", "i4"), ("b", "i4"), ("c", "i4")]
# is different from np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)], dtype=[("a", "i4"), ("b", "i4"), ("c", "i4")]).
# The list has the shape (3, 3) while the ndarray has the shape (3,).
# Therefore, do not modify the ndarray data.
if not isinstance(data, np.ndarray):
# If only some data is a Snowpark pandas object, convert it to pandas objects.
res = [
v.to_pandas()
if isinstance(v, (Index, BasePandasDataset))
else v
for v in data
]
data = res
query_compiler = from_pandas(
native_pd.DataFrame(
data=data,
# Handle setting the index, if it is a lazy index, outside this block in STEP 4.
index=None if isinstance(index, (Index, Series)) else index,
columns=columns,
dtype=dtype,
copy=copy,
)
)._query_compiler
# STEP 4: Setting the index
# -------------------------
# The index is already set if the data and index are non-Snowpark pandas objects.
# 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, Series))
or isinstance(data, (Index, BasePandasDataset))
):
if isinstance(data, (type(self), Series, type(None))):
# The `index` parameter is used to select the rows from `data` that will be in the resultant DataFrame.
# 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, set the 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 5: 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, BasePandasDataset))
and dtype != getattr(data, "dtype", None)
):
query_compiler = query_compiler.astype(
{col: dtype for col in query_compiler.columns}
)
# STEP 6: Setting the query compiler
# ----------------------------------
self._query_compiler = query_compiler
def _df_init_dict_data_with_snowpark_pandas_values(
data: AnyArrayLike | list,
index: list | AnyArrayLike | Series | Index,
columns: list | AnyArrayLike | Series | Index,
dtype: str | np.dtype | native_pd.ExtensionDtype | None,
) -> SnowflakeQueryCompiler:
"""
Helper function for initializing a DataFrame with a dictionary where all the values
are Snowpark pandas objects.
"""
# Special case: data is a dict where all the values are Snowpark pandas objects.
# Concat can only be performed with BasePandasDataset objects.
# If a value is an Index, convert it to a Series where the index is the index to be set since these values
# are always present in the final DataFrame.
from snowflake.snowpark.modin.plugin.extensions.general_overrides import concat
values = [
Series(v, index=index) if isinstance(v, Index) else v for v in data.values()
]
new_qc = concat(values, axis=1, keys=data.keys())._query_compiler
if dtype is not None:
new_qc = new_qc.astype({col: dtype for col in new_qc.columns})
if index is not None:
new_qc = new_qc.reindex(axis=0, labels=convert_index_to_qc(index))
if columns is not None:
new_qc = new_qc.reindex(axis=1, labels=columns)
return new_qc
def _df_init_list_data_with_snowpark_pandas_values(
data: AnyArrayLike | list,
index: list | AnyArrayLike | Series | Index,
columns: list | AnyArrayLike | Series | Index,
dtype: str | np.dtype | native_pd.ExtensionDtype | None,
):
"""
Helper function for initializing a DataFrame with a list where all the values
are Snowpark pandas objects.
"""
# Special case: data is a list/dict where all the values are Snowpark pandas objects.
# Concat can only be performed with BasePandasDataset objects.
# If a value is an Index, convert it to a Series.
from snowflake.snowpark.modin.plugin.extensions.general_overrides import concat
values = [Series(v) if isinstance(v, Index) else v for v in data]
new_qc = concat(values, axis=1).T._query_compiler
if dtype is not None:
new_qc = new_qc.astype({col: dtype for col in new_qc.columns})
if index is not None:
new_qc = new_qc.set_index([convert_index_to_qc(index)])
if columns is not None:
if all(isinstance(v, Index) for v in data):
# Special case: if all the values are Index objects, they are always present in the
# final result with the provided column names. Therefore, rename the columns.
new_qc = new_qc.set_columns(columns)
else:
new_qc = new_qc.reindex(axis=1, labels=columns)
return new_qc
@register_dataframe_accessor("__dataframe__")
def __dataframe__(
self, nan_as_null: bool = False, allow_copy: bool = True
) -> InterchangeDataframe:
return self._query_compiler.to_dataframe(
nan_as_null=nan_as_null, allow_copy=allow_copy
)
# Snowpark pandas defaults to axis=1 instead of axis=0 for these; we need to investigate if the same should
# apply to upstream Modin.
@register_dataframe_accessor("__and__")
def __and__(self, other):
# TODO: SNOW-1063346: Modin upgrade - modin.pandas.DataFrame functions
return self._binary_op("__and__", other, axis=1)
@register_dataframe_accessor("__rand__")
def __rand__(self, other):
# TODO: SNOW-1063346: Modin upgrade - modin.pandas.DataFrame functions
return self._binary_op("__rand__", other, axis=1)
@register_dataframe_accessor("__or__")
def __or__(self, other):
# TODO: SNOW-1063346: Modin upgrade - modin.pandas.DataFrame functions
return self._binary_op("__or__", other, axis=1)
@register_dataframe_accessor("__ror__")
def __ror__(self, other):
# TODO: SNOW-1063346: Modin upgrade - modin.pandas.DataFrame functions
return self._binary_op("__ror__", other, axis=1)
# Upstream Modin defaults to pandas in some cases.
@register_dataframe_accessor("apply")
def apply(
self,
func: AggFuncType | UserDefinedFunction,
axis: Axis = 0,
raw: bool = False,
result_type: Literal["expand", "reduce", "broadcast"] | None = None,
args=(),
**kwargs,
):
"""
Apply a function along an axis of the ``DataFrame``.
"""
# TODO: SNOW-1063346: Modin upgrade - modin.pandas.DataFrame functions
axis = self._get_axis_number(axis)
query_compiler = self._query_compiler.apply(
func,
axis,
raw=raw,
result_type=result_type,
args=args,
**kwargs,
)
if not isinstance(query_compiler, type(self._query_compiler)):
# A scalar was returned
return query_compiler
# If True, it is an unamed series.
# Theoretically, if df.apply returns a Series, it will only be an unnamed series
# because the function is supposed to be series -> scalar.
if query_compiler._modin_frame.is_unnamed_series():
return Series(query_compiler=query_compiler)
else:
return self.__constructor__(query_compiler=query_compiler)
# Snowpark pandas uses a separate QC method, while modin directly calls map.
@register_dataframe_accessor("applymap")
def applymap(self, func: PythonFuncType, na_action: str | None = None, **kwargs):
warnings.warn(
"DataFrame.applymap has been deprecated. Use DataFrame.map instead.",
FutureWarning,
stacklevel=2,
)
return self.map(func, na_action=na_action, **kwargs)
# We need to override _get_columns to satisfy
# tests/unit/modin/test_type_annotations.py::test_properties_snow_1374293[_get_columns-type_hints1]
# since Modin doesn't provide this type hint.
def _get_columns(self) -> native_pd.Index:
"""
Get the columns for this Snowpark pandas ``DataFrame``.
Returns
-------
Index
The all columns.
"""
# TODO: SNOW-1063346: Modin upgrade - modin.pandas.DataFrame functions
return self._query_compiler.columns
# Snowpark pandas wraps this in an update_in_place
def _set_columns(self, new_columns: Axes) -> None:
"""
Set the columns for this Snowpark pandas ``DataFrame``.
Parameters
----------
new_columns :
The new columns to set.
"""
# TODO: SNOW-1063346: Modin upgrade - modin.pandas.DataFrame functions
self._update_inplace(
new_query_compiler=self._query_compiler.set_columns(new_columns)
)
register_dataframe_accessor("columns")(property(_get_columns, _set_columns))
# Snowpark pandas does preprocessing for numeric_only (should be pushed to QC).
@register_dataframe_accessor("corr")
def corr(
self,
method: str | Callable = "pearson",
min_periods: int | None = None,
numeric_only: bool = False,
): # noqa: PR01, RT01, D200
"""
Compute pairwise correlation of columns, excluding NA/null values.
"""
# TODO: SNOW-1063346: Modin upgrade - modin.pandas.DataFrame functions
corr_df = self
if numeric_only:
corr_df = self.drop(
columns=[
i for i in self.dtypes.index if not is_numeric_dtype(self.dtypes[i])
]
)
return self.__constructor__(
query_compiler=corr_df._query_compiler.corr(
method=method,
min_periods=min_periods,
)
)
# Snowpark pandas does not respect `ignore_index`, and upstream Modin does not respect `how`.
@register_dataframe_accessor("dropna")
def dropna(
self,
*,
axis: Axis = 0,
how: str | NoDefault = no_default,
thresh: int | NoDefault = no_default,
subset: IndexLabel = None,
inplace: bool = False,
): # TODO: SNOW-1063346: Modin upgrade - modin.pandas.DataFrame functions
return super(DataFrame, self)._dropna(
axis=axis, how=how, thresh=thresh, subset=subset, inplace=inplace
)
# Snowpark pandas uses `self_is_series`, while upstream Modin uses `squeeze_self` and `squeeze_value`.
@register_dataframe_accessor("fillna")
def fillna(
self,
value: Hashable | Mapping | Series | DataFrame = None,
*,
method: FillnaOptions | None = None,
axis: Axis | None = None,
inplace: bool = False,
limit: int | None = None,
downcast: dict | None = None,
) -> DataFrame | None:
# TODO: SNOW-1063346: Modin upgrade - modin.pandas.DataFrame functions
return super(DataFrame, self).fillna(
self_is_series=False,
value=value,
method=method,
axis=axis,
inplace=inplace,
limit=limit,
downcast=downcast,
)
# Snowpark pandas does different validation and returns a custom GroupBy object.
@register_dataframe_accessor("groupby")
def groupby(
self,
by=None,
axis: Axis | NoDefault = no_default,
level: IndexLabel | None = None,