-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathapply_utils.py
More file actions
1635 lines (1471 loc) · 67.9 KB
/
apply_utils.py
File metadata and controls
1635 lines (1471 loc) · 67.9 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.
#
import inspect
import json
import sys
from collections import namedtuple
from collections.abc import Hashable
from enum import Enum, auto
from typing import Any, Callable, Literal, Optional, Union
from datetime import datetime
import cloudpickle
import numpy as np
import pandas as native_pd
import snowflake.cortex
from pandas._typing import AggFuncType
from pandas.api.types import is_scalar
from snowflake.snowpark import functions
from snowflake.snowpark._internal.type_utils import PYTHON_TO_SNOW_TYPE_MAPPINGS
from collections.abc import Mapping
from snowflake.snowpark._internal.udf_utils import get_types_from_type_hints
import functools
from snowflake.snowpark.column import Column as SnowparkColumn
from snowflake.snowpark.modin.plugin._internal.snowpark_pandas_types import (
TimedeltaType,
)
from snowflake.snowpark.modin.plugin._internal.type_utils import (
infer_object_type,
pandas_lit,
is_compatible_snowpark_types,
)
from snowflake.snowpark import functions as sp_func
from snowflake.snowpark.modin.plugin._internal.frame import InternalFrame
from snowflake.snowpark.modin.plugin._internal.ordered_dataframe import (
OrderedDataFrame,
OrderingColumn,
)
from snowflake.snowpark.modin.plugin._internal.utils import (
TempObjectType,
generate_snowflake_quoted_identifiers_helper,
parse_object_construct_snowflake_quoted_identifier_and_extract_pandas_label,
parse_snowflake_object_construct_identifier_to_map,
)
from snowflake.snowpark.modin.plugin.utils.error_message import ErrorMessage
import itertools
from collections import defaultdict
from snowflake.snowpark.modin.utils import MODIN_UNNAMED_SERIES_LABEL
from snowflake.snowpark.session import Session
from snowflake.snowpark.types import (
ArrayType,
BinaryType,
BooleanType,
DataType,
_IntegralType,
_FractionalType,
IntegerType,
LongType,
MapType,
NullType,
PandasDataFrameType,
PandasSeriesType,
StringType,
TimestampType,
VariantType,
)
from snowflake.snowpark.udf import UserDefinedFunction
from snowflake.snowpark.udtf import UserDefinedTableFunction
from snowflake.snowpark.window import Window
APPLY_LABEL_COLUMN_QUOTED_IDENTIFIER = '"LABEL"'
APPLY_VALUE_COLUMN_QUOTED_IDENTIFIER = '"VALUE"'
# Default partition size to use when applying a UDTF. A higher value results in less parallelism, less contention and higher batching.
DEFAULT_UDTF_PARTITION_SIZE = 1000
# Use the workaround described below to use functions that are attributes of
# this module in UDFs and UDTFs. Without this workaround, we can't pickle
# those functions.
# https://github.com/cloudpipe/cloudpickle?tab=readme-ov-file#overriding-pickles-serialization-mechanism-for-importable-constructs
cloudpickle.register_pickle_by_value(sys.modules[__name__])
SUPPORTED_SNOWPARK_PYTHON_FUNCTIONS_IN_APPLY = {
sp_func.exp,
sp_func.ln,
sp_func.log,
sp_func._log2,
sp_func._log10,
sp_func.sin,
sp_func.cos,
sp_func.tan,
sp_func.sinh,
sp_func.cosh,
sp_func.tanh,
sp_func.ceil,
sp_func.floor,
sp_func.trunc,
sp_func.sqrt,
}
SUPPORTED_SNOWFLAKE_CORTEX_FUNCTIONS_IN_APPLY = {
snowflake.cortex.Summarize,
snowflake.cortex.Sentiment,
}
ALL_SNOWFLAKE_CORTEX_FUNCTIONS = tuple(
i[1] for i in inspect.getmembers(snowflake.cortex)
)
class GroupbyApplySortMethod(Enum):
"""
A rule for sorting the rows resulting from groupby.apply.
"""
UNSET = auto()
# order by order of the input row that each output row originated from.
ORIGINAL_ROW_ORDER = auto()
# order by 1) comparing the group keys to each other 2) resolving
# ties by the order within the result for each group. this is like
# "sort=True" for groupby aggregations.
GROUP_KEY_COMPARISON_ORDER = auto()
# order by 1) ordering by the order in which the group keys appear
# in the original frame 2) resolving ties by the order within the
# result for each group. this is like "sort=false" for groupby
# aggregations.
GROUP_KEY_APPEARANCE_ORDER = auto()
def check_return_variant_and_get_return_type(func: Callable) -> tuple[bool, DataType]:
"""Check whether the function returns a variant in Snowflake, and get its return type."""
return_type = deduce_return_type_from_function(func, None)
if return_type is None or isinstance(
return_type, (VariantType, PandasSeriesType, PandasDataFrameType)
):
# By default, we assume it is a series-to-series function
# However, vectorized UDF only allows returning one column
# We will convert the result series to a list, which will be
# returned as a Variant
return_variant = True
else:
return_variant = False
return return_variant, return_type
def create_udtf_for_apply_axis_1(
row_position_snowflake_quoted_identifier: str,
func: Union[Callable, UserDefinedFunction],
raw: bool,
result_type: Optional[Literal["expand", "reduce", "broadcast"]],
args: tuple,
column_index: native_pd.Index,
input_types: list[DataType],
session: Session,
**kwargs: Any,
) -> UserDefinedTableFunction:
"""
Creates a wrapper UDTF for `func` to produce narrow table results for row-wise `df.apply` (i.e., `axis=1`).
The UDTF produces 3 columns: row position column, label column and value column.
The label column maintains a json string from a dict, which contains
a pandas label in the current series, and its occurrence. We need to
record the occurrence to deduplicate the duplicate labels so the later pivot
operation on the label column can create separate columns on duplicate labels.
The value column maintains the value of the result after applying `func`.
Args:
row_position_snowflake_quoted_identifier: quoted identifier identifying the row position column passed into the UDTF.
func: The UDF to apply row-wise.
raw: pandas parameter controlling apply within the UDTF.
result_type: pandas parameter controlling apply within the UDTF.
args: pandas parameter controlling apply within the UDTF.
column_index: The columns of the callee DataFrame, i.e. df.columns as pd.Index object.
input_types: Snowpark column types of the input data columns.
**kwargs: pandas parameter controlling apply within the UDTF.
Returns:
Snowpark vectorized UDTF producing 3 columns.
"""
# If given as Snowpark function, extract packages.
udf_packages = []
if isinstance(func, UserDefinedFunction):
# TODO: Cover will be achieved with SNOW-1261830.
udf_packages = func._packages # pragma: no cover
func = func.func # pragma: no cover
class ApplyFunc:
def end_partition(self, df): # type: ignore[no-untyped-def] # pragma: no cover
# First column is row position, set as index.
df = df.set_index(df.columns[0])
df.columns = column_index
df = df.apply(
func, axis=1, raw=raw, result_type=result_type, args=args, **kwargs
)
# When a dataframe is returned from `df.apply`,
# `func` is a series-to-series function, e.g.,
# def func(row):
# result = row + 1
# result.index.name = 'new_index_name'
# return result
#
# For example, the original dataframe is
# a b b
# 0 0 1 2
#
# the result dataframe from `df.apply` is
# new_index_name a b b
# 0 1 2 3
# After the transformation below, we will get a dataframe with two
# columns. Each row in the result represents the series result
# at a particular position.
# "LABEL" "VALUE"
# 0 {"pos": 0, "0": "a", "names": ["new_index_name"]} 1
# 1 {"pos": 1, "0": "b", "names": ["new_index_name"]} 2
# 2 {"pos": 2, "0": "b", "names": ["new_index_name"]} 3
# where:
# - `pos` indicates the position within the series.
# - The integer keys like "0" map from index level to the result's
# label at that level. In this case, the result only has one
# index level.
# - `names` contains the names of the result's index levels.
# - VALUE contains the result at this position.
if isinstance(df, native_pd.DataFrame):
result = []
for row_position_index, series in df.iterrows():
for i, (label, value) in enumerate(series.items()):
# If this is a tuple then we store each component with a 0-based
# lookup. For example, (a,b,c) is stored as (0:a, 1:b, 2:c).
if isinstance(label, tuple):
obj_label = {k: v for k, v in enumerate(list(label))}
else:
obj_label = {0: label}
obj_label["names"] = series.index.names
obj_label["pos"] = i
result.append(
[
row_position_index,
json.dumps(obj_label),
value,
]
)
# use object type so the result is json-serializable
result = native_pd.DataFrame(
result, columns=["__row__", "label", "value"], dtype=object
)
# When a series is returned from `df.apply`,
# `func` is a series-to-scalar function, e.g., `np.sum`
# For example, the original dataframe is
# a b
# 0 1 2
# and the result series from `df.apply` is
# 0 3
# dtype: int64
# After the transformation below, we will get a dataframe with two columns:
# "LABEL" "VALUE"
# 0 {'0': MODIN_UNNAMED_SERIES_LABEL} 3
elif isinstance(df, native_pd.Series):
result = df.to_frame(name="value")
result.insert(0, "label", json.dumps({"0": MODIN_UNNAMED_SERIES_LABEL}))
result.reset_index(names="__row__", inplace=True)
else:
raise TypeError(f"Unsupported data type {df} from df.apply")
result["value"] = (
result["value"]
.apply(
lambda v: handle_missing_value_in_variant(
convert_numpy_int_result_to_int(v)
)
)
.astype(object)
)
return result
ApplyFunc.end_partition._sf_vectorized_input = native_pd.DataFrame # type: ignore[attr-defined]
packages = list(session.get_packages().values()) + udf_packages
func_udtf = sp_func.udtf(
ApplyFunc,
output_schema=PandasDataFrameType(
[LongType(), StringType(), VariantType()],
[
row_position_snowflake_quoted_identifier,
APPLY_LABEL_COLUMN_QUOTED_IDENTIFIER,
APPLY_VALUE_COLUMN_QUOTED_IDENTIFIER,
],
),
input_types=[PandasDataFrameType([LongType()] + input_types)],
# We have to use the current pandas version to ensure the behavior consistency
packages=[native_pd] + packages,
session=session,
)
return func_udtf
def convert_groupby_apply_dataframe_result_to_standard_schema(
func_input_df: native_pd.DataFrame,
func_output_df: native_pd.DataFrame,
input_row_positions: native_pd.Series,
include_index_columns: bool,
) -> native_pd.DataFrame: # pragma: no cover: this function runs inside a UDTF, so coverage tools can't detect that we are testing it.
"""
Take the result of applying the user-provided function to a dataframe, and convert it to a dataframe with known schema that we can output from a vUDTF.
Args:
func_input_df: The input to `func`, where `func` is the Python function
that the user originally passed to apply().
func_output_df: The output of `func`.
input_row_positions: The original row positions of the rows that
func_input_df came from.
include_index_columns: Whether to include the result's index columns in
the output.
Returns:
A 5-column dataframe that represents the function result per the
description in create_udtf_for_groupby_apply.
"""
result_rows = []
result_index_names = func_output_df.index.names
is_transform = func_output_df.index.equals(func_input_df.index)
for row_number, (index_label, row) in enumerate(func_output_df.iterrows()):
output_row_number = input_row_positions.iloc[row_number] if is_transform else -1
if include_index_columns:
if isinstance(index_label, tuple):
for k, v in enumerate(index_label):
result_rows.append(
[
json.dumps({"index_pos": k, "name": result_index_names[k]}),
row_number,
v,
output_row_number,
]
)
else:
result_rows.append(
[
json.dumps({"index_pos": 0, "name": result_index_names[0]}),
row_number,
index_label,
output_row_number,
]
)
for col_number, (label, value) in enumerate(row.items()):
obj_label: dict[Any, Any] = {}
if isinstance(label, tuple):
obj_label = {k: v for k, v in enumerate(list(label))}
else:
obj_label = {0: label}
obj_label["data_pos"] = col_number
obj_label["names"] = row.index.names
result_rows.append(
[
json.dumps(obj_label),
row_number,
convert_numpy_int_result_to_int(value),
output_row_number,
]
)
# use object type so the result is json-serializable
result_df = native_pd.DataFrame(
result_rows,
columns=[
"label",
"row_position_within_group",
"value",
"original_row_number",
],
dtype=object,
)
result_df["value"] = (
result_df["value"]
.apply(
lambda v: handle_missing_value_in_variant(
convert_numpy_int_result_to_int(v)
)
)
.astype(object)
)
result_df["first_position_for_group"] = input_row_positions.iloc[0]
return result_df
def create_groupby_transform_func(
func: Callable, by: str, level: Any, *args: Any, **kwargs: Any
) -> Callable:
"""
Helper function to create the groupby lambda required for DataFrameGroupBy.transform.
This is a workaround to prevent pickling DataFrame objects: the pickle module will
try to pickle all objects accessible to the function passed in.
Args
----
func: The function to create the groupby lambda required for DataFrameGroupBy.
by: The column(s) to group by.
level: If the axis is a MultiIndex (hierarchical), group by a particular level or levels.
Do not specify both by and level.
args: Function's positional arguments.
kwargs: Function's keyword arguments.
Returns
-------
A lambda function that can be used in place of func in groupby transform.
"""
# - `dropna` controls whether the NA values should be included as a group/be present
# in the group keys. Therefore, it must be False to ensure that no values are excluded.
# Setting `dropna=True` here raises the IndexError: "cannot do a non-empty take from an empty axes."
# This is because any dfs created from the NA group keys result in empty dfs to work with,
# which cannot be used with the `take` method.
#
# - `group_keys` controls whether the grouped column(s) are included in the index.
# - `sort` controls whether the group keys are sorted.
# - `as_index` controls whether the groupby object has group labels as the index.
# The index of the result of any transform call is guaranteed to be the original
# index. Therefore, the groupby parameters group_keys, sort, and as_index do not
# affect the result of transform, and are not explicitly specified.
return lambda df: (
df.groupby(by=by, level=level, dropna=False).transform(func, *args, **kwargs)
)
def create_udtf_for_groupby_apply(
func: Callable,
args: tuple,
kwargs: dict,
data_column_index: native_pd.Index,
index_column_names: list,
input_data_column_types: list[DataType],
input_index_column_types: list[DataType],
session: Session,
series_groupby: bool,
by_types: list[DataType],
existing_identifiers: list[str],
force_list_like_to_series: bool = False,
) -> UserDefinedTableFunction:
"""
Create a UDTF from the Python function for groupby.apply.
The UDTF takes as input the following columns in the listed order:
1. The original row position within the dataframe (not just within the group)
2. All the by columns (these are constant across the group, but in the case
# of SeriesGroupBy, we need these so we can name each input series by the
# group label)
3. All the index columns
4. All the data columns
The UDF returns as output the following columns in the listed order. There is
one row per result row and per result column.
1. The label for the row or index level value. This is a json string of a dict
representing the label.
For output rows representing data values, this looks like e.g. if the
data column ('a', 'int_col') is the 4th column, and the entire column
index has names ('l1', 'l2'):
{"data_pos": 4, "0": "a", "1": "int_col", "names": ["l1", "l2"]}
Note that "names" is common across all data columns.
For values of an index level, this looks like e.g. if the index level
3 has name "level_3":
{"index_pos": 3, name: "level_3"}
2. The row position of this result row within the group.
3. The value of the index level or the data column at this row.
4. For transforms, this gives the position of the input row that produced
this result row. We need this for transforms when group_keys=False
because we have to reindex the final result according to original row
position. If `func` is not a transform, this position is -1.
5. The position of the first row from the input dataframe that fell into
this group. For example, if we are grouping by column "A", we divide
the input dataframe into groups where column A is equal to "a1", where
it's equal to "a2", etc. We then apply `func` to each group. If "a2"
first appears in row position 0, then all output rows resulting from the
"a2" group get a value of 0 for this column. If "a1" first appears in
row position 1, then all output rows resulting from the "a1" group get
a value of 1 for this column. e.g.:
Input dataframe
---------------
position A B
0 a2 b0
1 a1 b1
2 a2 b2
Input Groups
------------
for group_key == a1:
A B
a1 b1
for group_key == a2:
A B
a1 b1
Output Groups
-------------
for group_key == a1:
first_appearance_position other result columns...
1 other result values....
for group_key == a2:
first_appearance_position other result columns...
0 other result values....
0 other result values....
Args
----
func: The function we need to apply to each group
args: Function's positional arguments
kwargs: Function's keyword arguments
data_column_index: Column labels for the input dataframe
index_column_names: Names of the input dataframe's index
input_data_column_types: Types of the input dataframe's data columns
input_index_column_types: Types of the input dataframe's index columns
session: the current session
series_groupby: Whether we are performing a SeriesGroupBy.apply() instead of DataFrameGroupBy.apply()
by_types: The snowflake types of the by columns.
existing_identifiers: List of existing column identifiers; these are omitted when creating new column identifiers.
force_list_like_to_series: Force the function result to series if it is list-like
Returns
-------
A UDTF that will apply the provided function to a group and return a
dataframe representing all the data and metadata of the result.
"""
# Get the length of this list outside the vUDTF function because the vUDTF
# doesn't have access to the Snowpark module, which defines these types.
num_by = len(by_types)
from snowflake.snowpark.modin.plugin.extensions.utils import (
try_convert_index_to_native,
)
data_column_index = try_convert_index_to_native(data_column_index)
class ApplyFunc:
def end_partition(self, df: native_pd.DataFrame): # type: ignore[no-untyped-def] # pragma: no cover: adding type hint causes an error when creating udtf. also, skip coverage for this function because coverage tools can't tell that we're executing this function because we execute it in a UDTF.
"""
Apply the user-provided function to the group represented by this partition.
Args
----
df: The dataframe representing one group
Returns
-------
A dataframe representing the result of applying the user-provided
function to this group.
"""
current_column_position = 0
# The first column is row position. Save it for later.
row_position_column_number = 0
row_positions = df.iloc[:, row_position_column_number]
current_column_position = row_position_column_number + 1
# The next columns are the by columns. Since we are only looking at
# one group, every row in the by columns is the same, so get the
# group label from the first row.
group_label = tuple(
df.iloc[0, current_column_position : current_column_position + num_by]
)
current_column_position = current_column_position + num_by
if len(group_label) == 1:
group_label = group_label[0]
df = df.iloc[:, current_column_position:]
# Snowflake names the original columns "ARG1", "ARG2", ... "ARGN".
# the columns after the by columns are the index columns.
df.set_index(
[
f"ARG{i}"
for i in range(
1 + current_column_position,
1 + current_column_position + len(index_column_names),
)
],
inplace=True,
)
df.index.names = index_column_names
if series_groupby:
# For SeriesGroupBy, there should be only one data column.
num_columns = len(df.columns)
assert (
num_columns == 1
), f"Internal error: SeriesGroupBy func should apply to series, but input data had {num_columns} columns."
input_object = df.iloc[:, 0].rename(group_label)
else:
input_object = df.set_axis(data_column_index, axis="columns")
# Use infer_objects() because integer columns come as floats
# TODO: file snowpark bug about that. Asked about this here:
# https://github.com/snowflakedb/snowpandas/pull/823/files#r1507286892
input_object = input_object.infer_objects()
func_result = func(input_object, *args, **kwargs)
if (
force_list_like_to_series
and not isinstance(func_result, native_pd.Series)
and native_pd.api.types.is_list_like(func_result)
):
if len(func_result) == 1:
func_result = func_result[0]
else:
func_result = native_pd.Series(func_result)
if len(func_result) == len(df.index):
func_result.index = df.index
if isinstance(func_result, native_pd.Series):
if series_groupby:
func_result_as_frame = func_result.to_frame()
func_result_as_frame.columns = [MODIN_UNNAMED_SERIES_LABEL]
else:
# If function returns series, we have to transpose the series
# and change its metadata a little bit, but after that we can
# continue largely as if the function has returned a dataframe.
#
# If the series has a 1-dimensional index, the series name
# becomes the name of the column index. For example, if
# `func` returned the series native_pd.Series([1], name='a'):
#
# 0 1
# Name: a, dtype: int64
#
# The result needs to use the dataframe
# pd.DataFrame([1], columns=pd.Index([0], name='a'):
#
# a 0
# 0 1
#
name = func_result.name
func_result.name = None
func_result_as_frame = func_result.to_frame().T
if func_result_as_frame.columns.nlevels == 1:
func_result_as_frame.columns.name = name
return convert_groupby_apply_dataframe_result_to_standard_schema(
input_object,
func_result_as_frame,
row_positions,
# For DataFrameGroupBy, we don't need to include any
# information about the index of `func_result_as_frame`.
# The series only has one index, and that index becomes the
# columns of `func_result_as_frame`. For SeriesGroupBy, we
# do include the result's index in the result.
include_index_columns=series_groupby,
)
if isinstance(func_result, native_pd.DataFrame):
return convert_groupby_apply_dataframe_result_to_standard_schema(
input_object, func_result, row_positions, include_index_columns=True
)
# At this point, we know the function result was not a DataFrame
# or Series
return native_pd.DataFrame(
{
"label": [
json.dumps({"0": MODIN_UNNAMED_SERIES_LABEL, "data_pos": 0})
],
"row_position_within_group": [0],
"value": [convert_numpy_int_result_to_int(func_result)],
"original_row_number": [-1],
"first_position_for_group": [row_positions.iloc[0]],
},
# use object dtype so result is JSON-serializable
dtype=object,
)
input_types = [
# first input column is the integer row number. the row number integer
# becomes a float inside the UDTF due to SNOW-1184587
LongType(),
# the next columns are the by columns...
*by_types,
# then the index columns for the input dataframe or series...
*input_index_column_types,
# ...then the data columns for the input dataframe or series.
*input_data_column_types,
]
col_labels = [
"LABEL",
"ROW_POSITION_WITHIN_GROUP",
"VALUE",
"ORIGINAL_ROW_POSITION",
"APPLY_FIRST_GROUP_KEY_OCCURRENCE_POSITION",
]
# Generate new column identifiers for all required UDTF columns with the helper below to prevent collisions in
# column identifiers.
col_names = generate_snowflake_quoted_identifiers_helper(
pandas_labels=col_labels,
excluded=existing_identifiers,
wrap_double_underscore=False,
)
return sp_func.udtf(
ApplyFunc,
output_schema=PandasDataFrameType(
[StringType(), IntegerType(), VariantType(), IntegerType(), IntegerType()],
col_names,
),
input_types=[PandasDataFrameType(col_types=input_types)],
# We have to specify the local pandas package so that the UDF's pandas
# behavior is consistent with client-side pandas behavior.
packages=[native_pd] + list(session.get_packages().values()),
session=session,
)
def create_udf_for_series_apply(
func: Union[Callable, UserDefinedFunction],
return_type: DataType,
input_type: DataType,
na_action: Optional[Literal["ignore"]],
session: Session,
args: tuple[Any, ...],
**kwargs: Any,
) -> UserDefinedFunction:
"""
Creates Snowpark user defined function to use like a columnar expression from given func or existing Snowpark user defined function.
Args:
func: a Python function or Snowpark user defined function.
return_type: return type of the function as Snowpark type.
input_type: input type of the function as Snowpark type.
na_action: if "ignore", use strict mode.
session: Snowpark session, should be identical with pd.session
args: positional arguments to pass to the UDF
**kwargs: keyword arguments to pass to the UDF
Returns:
Snowpark user defined function.
"""
# Start with session packages.
packages = list(session.get_packages().values())
# Snowpark function with annotations, extract underlying func to wrap.
if isinstance(func, UserDefinedFunction):
# Ensure return_type specified is identical.
assert (
func._return_type == return_type
), f"UserDefinedFunction has invalid return type {func.return_type} vs. {return_type}"
# Append packages from function.
if func._packages:
packages += func._packages
# Below the function func is wrapped again, extract here the underlying Python function.
func = func.func
if isinstance(return_type, VariantType):
def apply_func(x): # type: ignore[no-untyped-def] # pragma: no cover
result = []
# When the return type is Variant, the return value must be json-serializable
# Calling tolist() convert np.int*, np.bool*, etc. (which is not
# json-serializable) to python native values
for e in x.apply(func, args=args, **kwargs).tolist():
result.append(
handle_missing_value_in_variant(convert_numpy_int_result_to_int(e))
)
return result
else:
def apply_func(x): # type: ignore[no-untyped-def] # pragma: no cover
# TODO SNOW-1874779: Add verification here to ensure inferred type matches
# actual type.
return x.apply(func, args=args, **kwargs)
func_udf = sp_func.udf(
apply_func,
return_type=PandasSeriesType(return_type),
input_types=[PandasSeriesType(input_type)],
strict=bool(na_action == "ignore"),
session=session,
packages=packages,
)
return func_udf
def handle_missing_value_in_variant(value: Any) -> Any:
"""
Returns the correct NULL value in a variant column when a UDF is applied.
Snowflake supports two types of NULL values, JSON NULL and SQL NULL in variant data.
In Snowflake Python UDF, a VARIANT JSON NULL is translated to Python None and A SQL NULL is
translated to a Python object, which has the `is_sql_null` attribute.
See details in
https://docs.snowflake.com/en/user-guide/semistructured-considerations#null-values
https://docs.snowflake.com/en/developer-guide/udf/python/udf-python-designing#null-values
In Snowpark pandas apply/applymap API with a variant column, we return JSON NULL if a Python
None is returned in UDF (follow the same as Python UDF), and return SQL null for all other
pandas missing values (np.nan, pd.NA, pd.NaT). Note that pd.NA, pd.NaT are not
json-serializable, so we need to return a json-serializable value anyway (None or SqlNullWrapper())
"""
class SqlNullWrapper:
def __init__(self) -> None:
self.is_sql_null = True
if is_scalar(value) and native_pd.isna(value):
if value is None:
return None
else:
return SqlNullWrapper()
else:
return value
def convert_numpy_int_result_to_int(value: Any) -> Any:
"""
If the result is a numpy int (or bool), convert it to a python int (or bool.)
Use this function to make UDF results JSON-serializable. numpy ints are not
JSON-serializable, but python ints are. Note that this function cannot make
all results JSON-serializable, e.g. it will not convert make
[1, np.int64(3)] or [[np.int64(3)]] serializable by converting the numpy
ints to python ints. However, it's very common for functions to return
numpy integers or dataframes or series thereof, so if we apply this function
to the result (in case the function returns an integer) or each element of
the result (in case the function returns a dataframe or series), we can
make sure that we return a JSON-serializable column to snowflake.
Args
----
value: The value to fix
Returns
-------
int(value) if the value is a numpy int,
bool(value) if the value is a numpy bool, otherwise the value.
"""
return (
int(value)
if np.issubdtype(type(value), np.integer)
else (bool(value) if np.issubdtype(type(value), np.bool_) else value)
)
DUMMY_BOOL_INPUT = native_pd.Series([False, True])
# Note: we use only small dummy values here to avoid the risk of certain callables
# taking a long time to execute (where execution time is a function of the input value).
# As a downside this reduces diversity in input data so will reduce the effectiveness
# type inference framework in some rare cases.
DUMMY_INT_INPUT = native_pd.Series([-37, -9, -2, -1, 0, 2, 3, 5, 7, 9, 13, 16, 20, 101])
DUMMY_FLOAT_INPUT = native_pd.Series(
[-9.9, -2.2, -1.0, 0.0, 0.5, 0.33, None, 0.99, 2.0, 3.0, 5.0, 7.7, 9.898989, 100.1]
)
DUMMY_STRING_INPUT = native_pd.Series(
["", "a", "A", "0", "1", "01", "123", "-1", "-12", "true", "True", "false", "False"]
+ [None, "null", "Jane Smith", "janesmith@snowflake.com", "janesmith@gmail.com"]
+ ["650-592-4563", "Jane Smith, 123 Main St., Anytown, CA 12345"]
+ ["2020-12-23", "2020-12-23 12:34:56", "08/08/2024", "07-08-2022", "12:34:56"]
+ ["ABC", "bat-man", "super_man", "1@#$%^&*()_+", "<>?:{}|[]\\;'/.,", "<tag>"]
)
DUMMY_BINARY_INPUT = native_pd.Series(
[bytes("snow", "utf-8"), bytes("flake", "utf-8"), bytes("12", "utf-8"), None]
)
DUMMY_TIMESTAMP_INPUT = native_pd.to_datetime(
["2020-12-31 00:00:00", "2020-01-01 00:00:00", native_pd.Timestamp.min] # past
+ ["2090-01-01 00:00:00", "2090-12-31 00:00:00", native_pd.Timestamp.max] # future
+ [datetime.today(), None], # current
format="mixed",
)
def infer_return_type_using_dummy_data(
func: Callable, input_type: DataType, **kwargs: Any
) -> Optional[DataType]:
"""
Infer the return type of given function by applying it to a dummy input.
This method only supports the following input types: _IntegralType, _FractionalType,
StringType, BooleanType, TimestampType, BinaryType.
Args:
func: The function to infer the return type from.
input_type: The input type of the function.
**kwargs : Additional keyword arguments to pass as keywords arguments to func.
Returns:
The inferred return type of the function. If the return type cannot be inferred,
return None.
"""
if input_type is None:
return None
input_data = None
if isinstance(input_type, _IntegralType):
input_data = DUMMY_INT_INPUT
elif isinstance(input_type, _FractionalType):
input_data = DUMMY_FLOAT_INPUT
elif isinstance(input_type, StringType):
input_data = DUMMY_STRING_INPUT
elif isinstance(input_type, BooleanType):
input_data = DUMMY_BOOL_INPUT
elif isinstance(input_type, TimestampType):
input_data = DUMMY_TIMESTAMP_INPUT
elif isinstance(input_type, BinaryType):
input_data = DUMMY_BINARY_INPUT
else:
return None
def merge_types(t1: DataType, t2: DataType) -> DataType:
"""
Merge two types into one as per the following rules:
- Null + T = T
- T + Null = T
- T1 + T2 = T1 where T1 == T2
- T1 + T2 = Variant where T1 != T2
Args:
t1: first type to merge.
t2: second type to merge.
Returns:
Merged type of t1 and t2.
"""
# treat NullType as None
t1 = None if t1 == NullType() else t1
t2 = None if t2 == NullType() else t2
if t1 is None:
return t2
if t2 is None:
return t1
if t1 == t2:
return t1
if isinstance(t1, MapType) and isinstance(t2, MapType):
return MapType(
merge_types(t1.key_type, t2.key_type),
merge_types(t1.value_type, t2.value_type),
)
if isinstance(t1, ArrayType) and isinstance(t2, ArrayType):
return ArrayType(merge_types(t1.element_type, t2.element_type))
return VariantType()
inferred_type = None
for x in input_data:
try:
inferred_type = merge_types(
inferred_type, infer_object_type(func(x, **kwargs))
)
except Exception:
pass
if isinstance(inferred_type, TimedeltaType):
# TODO: SNOW-1619940: pd.Timedelta is encoded as string.
return StringType()
return inferred_type
def deduce_return_type_from_function(
func: Union[AggFuncType, UserDefinedFunction],
input_type: Optional[DataType],
**kwargs: Any,
) -> Optional[DataType]:
"""
Deduce return type if possible from a function, list, dict or type object. List will be mapped to ArrayType(),
dict to MapType(), and if a type object (e.g., str) is given a mapping will be consulted.
Args:
func: callable function, object or Snowpark UserDefinedFunction that can be passed in pandas to reference a function.
input_type: input data type this function is applied to.
**kwargs : Additional keyword arguments to pass as keywords arguments to func.
Returns:
Snowpark Datatype or None if no return type could be deduced.
"""
# Does function have an @udf decorator? Then return type from it directly.
if isinstance(func, UserDefinedFunction):
return func._return_type
# get the return type of type hints
# PYTHON_TO_SNOW_TYPE_MAPPINGS contains some Python builtin functions that
# can only return the certain type (e.g., `str` will return string)
# if we can't get the type hints from the function,
# use variant as the default, which can hold any type of value
if isinstance(func, list):
return ArrayType()
elif isinstance(func, dict):
return MapType()
elif func in PYTHON_TO_SNOW_TYPE_MAPPINGS:
return PYTHON_TO_SNOW_TYPE_MAPPINGS[func]()
else:
# handle special case 'object' type, in this case use Variant Type.
# Catch potential TypeError exception here from python_type_to_snow_type.
# If it is not the object type, return None to indicate that type hint could not
# be extracted successfully.
try:
return_type = get_types_from_type_hints(func, TempObjectType.FUNCTION)[0]
if return_type is not None: