/
functions.py
5804 lines (4688 loc) · 223 KB
/
functions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
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
#!/usr/bin/env python3
#
# Copyright (c) 2012-2023 Snowflake Computing Inc. All rights reserved.
#
"""
Provides utility and SQL functions that generate :class:`~snowflake.snowpark.Column` expressions that you can pass to :class:`~snowflake.snowpark.DataFrame` transformation methods.
These utility functions generate references to columns, literals, and SQL expressions (e.g. "c + 1").
- Use :func:`col()` to convert a column name to a :class:`Column` object. Refer to the API docs of :class:`Column` to know more ways of referencing a column.
- Use :func:`lit()` to convert a Python value to a :class:`Column` object that represents a constant value in Snowflake SQL.
- Use :func:`sql_expr()` to convert a Snowflake SQL expression to a :class:`Column`.
>>> df = session.create_dataframe([[1, 'a', True, '2022-03-16'], [3, 'b', False, '2023-04-17']], schema=["a", "b", "c", "d"])
>>> res1 = df.filter(col("a") == 1).collect()
>>> res2 = df.filter(lit(1) == col("a")).collect()
>>> res3 = df.filter(sql_expr("a = 1")).collect()
>>> assert res1 == res2 == res3
>>> res1
[Row(A=1, B='a', C=True, D='2022-03-16')]
Some :class:`DataFrame` methods accept column names or SQL expressions text aside from a Column object for convenience.
For instance:
>>> df.filter("a = 1").collect() # use the SQL expression directly in filter
[Row(A=1, B='a', C=True, D='2022-03-16')]
>>> df.select("a").collect()
[Row(A=1), Row(A=3)]
whereas :class:`Column` objects enable you to use chained column operators and transformations with
Python code fluently:
>>> # Use columns and literals in expressions.
>>> df.select(((col("a") + 1).cast("string")).alias("add_one")).show()
-------------
|"ADD_ONE" |
-------------
|2 |
|4 |
-------------
<BLANKLINE>
The Snowflake database has hundreds of `SQL functions <https://docs.snowflake.com/en/sql-reference-functions.html>`_
This module provides Python functions that correspond to the Snowflake SQL functions. They typically accept :class:`Column`
objects or column names as input parameters and return a new :class:`Column` objects.
The following examples demonstrate the use of some of these functions:
>>> # This example calls the function that corresponds to the TO_DATE() SQL function.
>>> df.select(dateadd('day', lit(1), to_date(col("d")))).show()
---------------------------------------
|"DATEADD('DAY', 1, TO_DATE(""D""))" |
---------------------------------------
|2022-03-17 |
|2023-04-18 |
---------------------------------------
<BLANKLINE>
If you want to use a SQL function in Snowflake but can't find the corresponding Python function here,
you can create your own Python function with :func:`function`:
>>> my_radians = function("radians") # "radians" is the SQL function name.
>>> df.select(my_radians(col("a")).alias("my_radians")).show()
------------------------
|"MY_RADIANS" |
------------------------
|0.017453292519943295 |
|0.05235987755982988 |
------------------------
<BLANKLINE>
or call the SQL function directly:
>>> df.select(call_function("radians", col("a")).as_("call_function_radians")).show()
---------------------------
|"CALL_FUNCTION_RADIANS" |
---------------------------
|0.017453292519943295 |
|0.05235987755982988 |
---------------------------
<BLANKLINE>
Similarly, to call a table function, you can use :func:`~snowflake.snowpark.functions.table_function`, or :func:`~snowflake.snowpark.functions.call_table_function`.
**How to find help on input parameters of the Python functions for SQL functions**
The Python functions have the same name as the corresponding `SQL functions <https://docs.snowflake.com/en/sql-reference-functions.html>`_.
By reading the API docs or the source code of a Python function defined in this module, you'll see the type hints of the input parameters and return type.
The return type is always ``Column``. The input types tell you the acceptable values:
- ``ColumnOrName`` accepts a :class:`Column` object, or a column name in str. Most functions accept this type.
If you still want to pass a literal to it, use `lit(value)`, which returns a ``Column`` object that represents a literal value.
>>> df.select(avg("a")).show()
----------------
|"AVG(""A"")" |
----------------
|2.000000 |
----------------
<BLANKLINE>
>>> df.select(avg(col("a"))).show()
----------------
|"AVG(""A"")" |
----------------
|2.000000 |
----------------
<BLANKLINE>
- ``LiteralType`` accepts a value of type ``bool``, ``int``, ``float``, ``str``, ``bytearray``, ``decimal.Decimal``,
``datetime.date``, ``datetime.datetime``, ``datetime.time``, or ``bytes``. An example is the third parameter of :func:`lead`.
>>> import datetime
>>> from snowflake.snowpark.window import Window
>>> df.select(col("d"), lead("d", 1, datetime.date(2024, 5, 18), False).over(Window.order_by("d")).alias("lead_day")).show()
---------------------------
|"D" |"LEAD_DAY" |
---------------------------
|2022-03-16 |2023-04-17 |
|2023-04-17 |2024-05-18 |
---------------------------
<BLANKLINE>
- ``ColumnOrLiteral`` accepts a ``Column`` object, or a value of ``LiteralType`` mentioned above.
The difference from ``ColumnOrLiteral`` is ``ColumnOrLiteral`` regards a str value as a SQL string value instead of
a column name. When a function is much more likely to accept a SQL constant value than a column expression, ``ColumnOrLiteral``
is used. Yet you can still pass in a ``Column`` object if you need to. An example is the second parameter of
:func:``when``.
>>> df.select(when(df["a"] > 2, "Greater than 2").else_("Less than 2").alias("compare_with_2")).show()
--------------------
|"COMPARE_WITH_2" |
--------------------
|Less than 2 |
|Greater than 2 |
--------------------
<BLANKLINE>
- ``int``, ``bool``, ``str``, or another specific type accepts a value of that type. An example is :func:`to_decimal`.
>>> df.with_column("e", lit("1.2")).select(to_decimal("e", 5, 2)).show()
-----------------------------
|"TO_DECIMAL(""E"", 5, 2)" |
-----------------------------
|1.20 |
|1.20 |
-----------------------------
<BLANKLINE>
- ``ColumnOrSqlExpr`` accepts a ``Column`` object, or a SQL expression. For instance, the first parameter in :func:``when``.
>>> df.select(when("a > 2", "Greater than 2").else_("Less than 2").alias("compare_with_2")).show()
--------------------
|"COMPARE_WITH_2" |
--------------------
|Less than 2 |
|Greater than 2 |
--------------------
<BLANKLINE>
"""
import functools
import typing
from random import randint
from types import ModuleType
from typing import Callable, Dict, List, Optional, Tuple, Union, overload
import snowflake.snowpark
import snowflake.snowpark.table_function
from snowflake.snowpark._internal.analyzer.expression import (
CaseWhen,
FunctionExpression,
ListAgg,
Literal,
MultipleExpression,
Star,
)
from snowflake.snowpark._internal.analyzer.window_expression import (
FirstValue,
Lag,
LastValue,
Lead,
)
from snowflake.snowpark._internal.type_utils import (
ColumnOrLiteral,
ColumnOrLiteralStr,
ColumnOrName,
ColumnOrSqlExpr,
LiteralType,
)
from snowflake.snowpark._internal.utils import (
parse_positional_args_to_list,
validate_object_name,
)
from snowflake.snowpark.column import (
CaseExpr,
Column,
_to_col_if_sql_expr,
_to_col_if_str,
_to_col_if_str_or_int,
)
from snowflake.snowpark.stored_procedure import StoredProcedure
from snowflake.snowpark.types import DataType, FloatType, StructType
from snowflake.snowpark.udf import UserDefinedFunction
from snowflake.snowpark.udtf import UserDefinedTableFunction
# Python 3.8 needs to use typing.Iterable because collections.abc.Iterable is not subscriptable
# Python 3.9 can use both
# Python 3.10 needs to use collections.abc.Iterable because typing.Iterable is removed
try:
from typing import Iterable
except ImportError:
from collections.abc import Iterable
def col(col_name: str) -> Column:
"""Returns the :class:`~snowflake.snowpark.Column` with the specified name.
Example::
>>> df = session.sql("select 1 as a")
>>> df.select(col("a")).collect()
[Row(A=1)]
"""
return Column(col_name)
def column(col_name: str) -> Column:
"""Returns a :class:`~snowflake.snowpark.Column` with the specified name. Alias for col.
Example::
>>> df = session.sql("select 1 as a")
>>> df.select(column("a")).collect()
[Row(A=1)]
"""
return Column(col_name)
def lit(literal: LiteralType) -> Column:
"""
Creates a :class:`~snowflake.snowpark.Column` expression for a literal value.
It supports basic Python data types, including ``int``, ``float``, ``str``,
``bool``, ``bytes``, ``bytearray``, ``datetime.time``, ``datetime.date``,
``datetime.datetime`` and ``decimal.Decimal``. Also, it supports Python structured data types,
including ``list``, ``tuple`` and ``dict``, but this container must
be JSON serializable.
Example::
>>> import datetime
>>> columns = [lit(1), lit("1"), lit(1.0), lit(True), lit(b'snow'), lit(datetime.date(2023, 2, 2)), lit([1, 2]), lit({"snow": "flake"})]
>>> session.create_dataframe([[]]).select([c.as_(str(i)) for i, c in enumerate(columns)]).show()
---------------------------------------------------------------------------------------
|"0" |"1" |"2" |"3" |"4" |"5" |"6" |"7" |
---------------------------------------------------------------------------------------
|1 |1 |1.0 |True |bytearray(b'snow') |2023-02-02 |[ |{ |
| | | | | | | 1, | "snow": "flake" |
| | | | | | | 2 |} |
| | | | | | |] | |
---------------------------------------------------------------------------------------
<BLANKLINE>
"""
return literal if isinstance(literal, Column) else Column(Literal(literal))
def sql_expr(sql: str) -> Column:
"""Creates a :class:`~snowflake.snowpark.Column` expression from raw SQL text.
Note that the function does not interpret or check the SQL text."""
return Column._expr(sql)
def current_session() -> Column:
"""
Returns a unique system identifier for the Snowflake session corresponding to the present connection.
This will generally be a system-generated alphanumeric string. It is NOT derived from the user name or user account.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> result = session.create_dataframe([1]).select(current_session()).collect()
>>> assert result[0]['CURRENT_SESSION()'] is not None
"""
return builtin("current_session")()
def current_statement() -> Column:
"""
Returns the SQL text of the statement that is currently executing.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> session.create_dataframe([1]).select(current_statement()).collect()
[Row(CURRENT_STATEMENT()='SELECT current_statement() FROM ( SELECT "_1" FROM ( SELECT $1 AS "_1" FROM VALUES (1 :: INT)))')]
"""
return builtin("current_statement")()
def current_user() -> Column:
"""
Returns the name of the user currently logged into the system.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> result = session.create_dataframe([1]).select(current_user()).collect()
>>> assert result[0]['CURRENT_USER()'] is not None
"""
return builtin("current_user")()
def current_version() -> Column:
"""
Returns the current Snowflake version.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> result = session.create_dataframe([1]).select(current_version()).collect()
>>> assert result[0]['CURRENT_VERSION()'] is not None
"""
return builtin("current_version")()
def current_warehouse() -> Column:
"""
Returns the name of the warehouse in use for the current session.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> result = session.create_dataframe([1]).select(current_warehouse()).collect()
>>> assert result[0]['CURRENT_WAREHOUSE()'] is not None
"""
return builtin("current_warehouse")()
def current_database() -> Column:
"""Returns the name of the database in use for the current session.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> result = session.create_dataframe([1]).select(current_database()).collect()
>>> assert result[0]['CURRENT_DATABASE()'] is not None
"""
return builtin("current_database")()
def current_role() -> Column:
"""Returns the name of the role in use for the current session.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> result = session.create_dataframe([1]).select(current_role()).collect()
>>> assert result[0]['CURRENT_ROLE()'] is not None
"""
return builtin("current_role")()
def current_schema() -> Column:
"""Returns the name of the schema in use for the current session.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> result = session.create_dataframe([1]).select(current_schema()).collect()
>>> assert result[0]['CURRENT_SCHEMA()'] is not None
"""
return builtin("current_schema")()
def current_schemas() -> Column:
"""Returns active search path schemas.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> result = session.create_dataframe([1]).select(current_schemas()).collect()
>>> assert result[0]['CURRENT_SCHEMAS()'] is not None
"""
return builtin("current_schemas")()
def current_region() -> Column:
"""Returns the name of the region for the account where the current user is logged in.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> result = session.create_dataframe([1]).select(current_region()).collect()
>>> assert result[0]['CURRENT_REGION()'] is not None
"""
return builtin("current_region")()
def current_available_roles() -> Column:
"""Returns a JSON string that lists all roles granted to the current user.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> result = session.create_dataframe([1]).select(current_available_roles()).collect()
>>> assert result[0]['CURRENT_AVAILABLE_ROLES()'] is not None
"""
return builtin("current_available_roles")()
def add_months(
date_or_timestamp: ColumnOrName, number_of_months: Union[Column, int]
) -> Column:
"""Adds or subtracts a specified number of months to a date or timestamp, preserving the end-of-month information.
Example:
>>> import datetime
>>> df = session.create_dataframe([datetime.date(2022, 4, 6)], schema=["d"])
>>> df.select(add_months("d", 4)).collect()[0][0]
datetime.date(2022, 8, 6)
"""
c = _to_col_if_str(date_or_timestamp, "add_months")
return builtin("add_months")(c, number_of_months)
def any_value(e: ColumnOrName) -> Column:
"""Returns a non-deterministic any value for the specified column.
This is an aggregate and window function.
Example:
>>> df = session.create_dataframe([[1, 2], [3, 4]], schema=["a", "b"])
>>> result = df.select(any_value("a")).collect()
>>> assert len(result) == 1 # non-deterministic value in result.
"""
c = _to_col_if_str(e, "any_value")
return call_builtin("any_value", c)
def bitnot(e: ColumnOrName) -> Column:
"""Returns the bitwise negation of a numeric expression.
Example:
>>> df = session.create_dataframe([1], schema=["a"])
>>> df.select(bitnot("a")).collect()[0][0]
-2
"""
c = _to_col_if_str(e, "bitnot")
return call_builtin("bitnot", c)
def bitshiftleft(to_shift_column: ColumnOrName, n: Union[Column, int]) -> Column:
"""Returns the bitwise negation of a numeric expression.
Example:
>>> df = session.create_dataframe([2], schema=["a"])
>>> df.select(bitshiftleft("a", 1)).collect()[0][0]
4
"""
c = _to_col_if_str(to_shift_column, "bitshiftleft")
return call_builtin("bitshiftleft", c, n)
def bitshiftright(to_shift_column: ColumnOrName, n: Union[Column, int]) -> Column:
"""Returns the bitwise negation of a numeric expression.
Example:
>>> df = session.create_dataframe([2], schema=["a"])
>>> df.select(bitshiftright("a", 1)).collect()[0][0]
1
"""
c = _to_col_if_str(to_shift_column, "bitshiftright")
return call_builtin("bitshiftright", c, n)
def convert_timezone(
target_timezone: ColumnOrName,
source_time: ColumnOrName,
source_timezone: Optional[ColumnOrName] = None,
) -> Column:
"""Converts the given source_time to the target timezone.
For timezone information, refer to the `Snowflake SQL convert_timezone notes <https://docs.snowflake.com/en/sql-reference/functions/convert_timezone.html#usage-notes>`_
Args:
target_timezone: The time zone to which the input timestamp should be converted.=
source_time: The timestamp to convert. When it's a TIMESTAMP_LTZ, use ``None`` for ``source_timezone``.
source_timezone: The time zone for the ``source_time``. Required for timestamps with no time zone (i.e. TIMESTAMP_NTZ). Use ``None`` if the timestamps have a time zone (i.e. TIMESTAMP_LTZ). Default is ``None``.
Note:
The sequence of the 3 params is different from the SQL function, which two overloads:
- ``CONVERT_TIMEZONE( <source_tz> , <target_tz> , <source_timestamp_ntz> )``
- ``CONVERT_TIMEZONE( <target_tz> , <source_timestamp> )``
The first parameter ``source_tz`` is optional. But in Python an optional argument shouldn't be placed at the first.
So ``source_timezone`` is after ``source_time``.
Example:
>>> import datetime
>>> from dateutil import tz
>>> datetime_with_tz = datetime.datetime(2022, 4, 6, 9, 0, 0, tzinfo=tz.tzoffset("myzone", -3600*7))
>>> datetime_with_no_tz = datetime.datetime(2022, 4, 6, 9, 0, 0)
>>> df = session.create_dataframe([[datetime_with_tz, datetime_with_no_tz]], schema=["a", "b"])
>>> result = df.select(convert_timezone(lit("UTC"), col("a")), convert_timezone(lit("UTC"), col("b"), lit("Asia/Shanghai"))).collect()
>>> result[0][0]
datetime.datetime(2022, 4, 6, 16, 0, tzinfo=<UTC>)
>>> result[0][1]
datetime.datetime(2022, 4, 6, 1, 0)
"""
source_tz = (
_to_col_if_str(source_timezone, "convert_timezone")
if source_timezone is not None
else None
)
target_tz = _to_col_if_str(target_timezone, "convert_timezone")
source_time_to_convert = _to_col_if_str(source_time, "convert_timezone")
if source_timezone is None:
return call_builtin("convert_timezone", target_tz, source_time_to_convert)
return call_builtin(
"convert_timezone", source_tz, target_tz, source_time_to_convert
)
def approx_count_distinct(e: ColumnOrName) -> Column:
"""Uses HyperLogLog to return an approximation of the distinct cardinality of the input (i.e. HLL(col1, col2, ... )
returns an approximation of COUNT(DISTINCT col1, col2, ... ))."""
c = _to_col_if_str(e, "approx_count_distinct")
return builtin("approx_count_distinct")(c)
def avg(e: ColumnOrName) -> Column:
"""Returns the average of non-NULL records. If all records inside a group are NULL,
the function returns NULL.
Example::
>>> df = session.create_dataframe([[1], [2], [2]], schema=["d"])
>>> df.select(avg(df.d).alias("result")).show()
------------
|"RESULT" |
------------
|1.666667 |
------------
<BLANKLINE>
"""
c = _to_col_if_str(e, "avg")
return builtin("avg")(c)
def corr(column1: ColumnOrName, column2: ColumnOrName) -> Column:
"""Returns the correlation coefficient for non-null pairs in a group.
Example:
>>> df = session.create_dataframe([[1, 2], [1, 2], [4, 5], [2, 3], [3, None], [4, None], [6,4]], schema=["a", "b"])
>>> df.select(corr(col("a"), col("b")).alias("result")).show()
---------------------
|"RESULT" |
---------------------
|0.813681508328809 |
---------------------
<BLANKLINE>
"""
c1 = _to_col_if_str(column1, "corr")
c2 = _to_col_if_str(column2, "corr")
return builtin("corr")(c1, c2)
def count(e: ColumnOrName) -> Column:
"""Returns either the number of non-NULL records for the specified columns, or the
total number of records.
Example:
>>> df = session.create_dataframe([[1], [None], [3], [4], [None]], schema=["a"])
>>> df.select(count(col("a")).alias("result")).show()
------------
|"RESULT" |
------------
|3 |
------------
<BLANKLINE>
>>> df.select(count("*").alias("result")).show()
------------
|"RESULT" |
------------
|5 |
------------
<BLANKLINE>
"""
c = _to_col_if_str(e, "count")
return (
builtin("count")(Literal(1))
if isinstance(c._expression, Star)
else builtin("count")(c._expression)
)
def count_distinct(*cols: ColumnOrName) -> Column:
"""Returns either the number of non-NULL distinct records for the specified columns,
or the total number of the distinct records.
Example:
>>> df = session.create_dataframe([[1, 2], [1, 2], [3, None], [2, 3], [3, None], [4, None]], schema=["a", "b"])
>>> df.select(count_distinct(col("a"), col("b")).alias("result")).show()
------------
|"RESULT" |
------------
|2 |
------------
<BLANKLINE>
>>> # The result should be 2 for {[1,2],[2,3]} since the rest are either duplicate or NULL records
"""
cs = [_to_col_if_str(c, "count_distinct") for c in cols]
return Column(
FunctionExpression("count", [c._expression for c in cs], is_distinct=True)
)
def covar_pop(column1: ColumnOrName, column2: ColumnOrName) -> Column:
"""Returns the population covariance for non-null pairs in a group.
Example:
>>> from snowflake.snowpark.types import DecimalType
>>> df = session.create_dataframe([[1, 2], [1, 2], [4, 5], [2, 3], [3, None], [4, None], [6,4]], schema=["a", "b"])
>>> df.select(covar_pop(col("a"), col("b")).cast(DecimalType(scale=3)).alias("result")).show()
------------
|"RESULT" |
------------
|1.840 |
------------
<BLANKLINE>
"""
col1 = _to_col_if_str(column1, "covar_pop")
col2 = _to_col_if_str(column2, "covar_pop")
return builtin("covar_pop")(col1, col2)
def covar_samp(column1: ColumnOrName, column2: ColumnOrName) -> Column:
"""Returns the sample covariance for non-null pairs in a group.
Example:
>>> from snowflake.snowpark.types import DecimalType
>>> df = session.create_dataframe([[1, 2], [1, 2], [4, 5], [2, 3], [3, None], [4, None], [6,4]], schema=["a", "b"])
>>> df.select(covar_samp(col("a"), col("b")).cast(DecimalType(scale=3)).alias("result")).show()
------------
|"RESULT" |
------------
|2.300 |
------------
<BLANKLINE>
"""
col1 = _to_col_if_str(column1, "covar_samp")
col2 = _to_col_if_str(column2, "covar_samp")
return builtin("covar_samp")(col1, col2)
def kurtosis(e: ColumnOrName) -> Column:
"""
Returns the population excess kurtosis of non-NULL records. If all records
inside a group are NULL, the function returns NULL.
Example::
>>> from snowflake.snowpark.functions import kurtosis
>>> df = session.create_dataframe([1, 3, 10, 1, 3], schema=["x"])
>>> df.select(kurtosis("x").as_("x")).collect()
[Row(X=Decimal('3.613736609956'))]
"""
c = _to_col_if_str(e, "kurtosis")
return builtin("kurtosis")(c)
def max(e: ColumnOrName) -> Column:
"""
Returns the maximum value for the records in a group. NULL values are ignored
unless all the records are NULL, in which case a NULL value is returned.
Example::
>>> df = session.create_dataframe([1, 3, 10, 1, 3], schema=["x"])
>>> df.select(max("x").as_("x")).collect()
[Row(X=10)]
"""
c = _to_col_if_str(e, "max")
return builtin("max")(c)
def mean(e: ColumnOrName) -> Column:
"""
Return the average for the specific numeric columns. Alias of :func:`avg`.
Example::
>>> df = session.create_dataframe([1, 3, 10, 1, 3], schema=["x"])
>>> df.select(mean("x").as_("x")).collect()
[Row(X=Decimal('3.600000'))]
"""
c = _to_col_if_str(e, "mean")
return avg(c)
def median(e: ColumnOrName) -> Column:
"""
Returns the median value for the records in a group. NULL values are ignored
unless all the records are NULL, in which case a NULL value is returned.
Example::
>>> df = session.create_dataframe([1, 3, 10, 1, 3], schema=["x"])
>>> df.select(median("x").as_("x")).collect()
[Row(X=Decimal('3.000'))]
"""
c = _to_col_if_str(e, "median")
return builtin("median")(c)
def min(e: ColumnOrName) -> Column:
"""
Returns the minimum value for the records in a group. NULL values are ignored
unless all the records are NULL, in which case a NULL value is returned.
Example::
>>> df = session.create_dataframe([1, 3, 10, 1, 3], schema=["x"])
>>> df.select(min("x").as_("x")).collect()
[Row(X=1)]
"""
c = _to_col_if_str(e, "min")
return builtin("min")(c)
def mode(e: ColumnOrName) -> Column:
"""
Returns the most frequent value for the records in a group. NULL values are ignored.
If all the values are NULL, or there are 0 rows, then the function returns NULL.
Example::
>>> df = session.create_dataframe([1, 3, 10, 1, 4], schema=["x"])
>>> df.select(mode("x").as_("x")).collect()
[Row(X=1)]
"""
c = _to_col_if_str(e, "mode")
return builtin("mode")(c)
def skew(e: ColumnOrName) -> Column:
"""Returns the sample skewness of non-NULL records. If all records inside a group
are NULL, the function returns NULL."""
c = _to_col_if_str(e, "skew")
return builtin("skew")(c)
def stddev(e: ColumnOrName) -> Column:
"""Returns the sample standard deviation (square root of sample variance) of
non-NULL values. If all records inside a group are NULL, returns NULL."""
c = _to_col_if_str(e, "stddev")
return builtin("stddev")(c)
def stddev_samp(e: ColumnOrName) -> Column:
"""Returns the sample standard deviation (square root of sample variance) of
non-NULL values. If all records inside a group are NULL, returns NULL. Alias of
:func:`stddev`."""
c = _to_col_if_str(e, "stddev_samp")
return builtin("stddev_samp")(c)
def stddev_pop(e: ColumnOrName) -> Column:
"""Returns the population standard deviation (square root of variance) of non-NULL
values. If all records inside a group are NULL, returns NULL."""
c = _to_col_if_str(e, "stddev_pop")
return builtin("stddev_pop")(c)
def sum(e: ColumnOrName) -> Column:
"""Returns the sum of non-NULL records in a group. You can use the DISTINCT keyword
to compute the sum of unique non-null values. If all records inside a group are
NULL, the function returns NULL."""
c = _to_col_if_str(e, "sum")
return builtin("sum")(c)
def sum_distinct(e: ColumnOrName) -> Column:
"""Returns the sum of non-NULL distinct records in a group. You can use the
DISTINCT keyword to compute the sum of unique non-null values. If all records
inside a group are NULL, the function returns NULL."""
c = _to_col_if_str(e, "sum_distinct")
return _call_function("sum", True, c)
def variance(e: ColumnOrName) -> Column:
"""Returns the sample variance of non-NULL records in a group. If all records
inside a group are NULL, a NULL is returned. For a single row, NULL is returned as sample variance.
Example::
>>> df = session.create_dataframe([1, -1, 1, -1, -1], schema=["a"])
>>> df.select(variance(col("a"))).collect()
[Row(VARIANCE("A")=Decimal('1.200000'))]
>>> df = session.create_dataframe([1, None, 2, 3, None, 5, 6], schema=["a"])
>>> df.select(variance(col("a"))).collect()
[Row(VARIANCE("A")=Decimal('4.300000'))]
>>> df = session.create_dataframe([None, None, None], schema=["a"])
>>> df.select(variance(col("a"))).collect()
[Row(VARIANCE("A")=None)]
>>> df = session.create_dataframe([42], schema=["a"])
>>> df.select(variance(col("a"))).collect()
[Row(VARIANCE("A")=None)]
"""
c = _to_col_if_str(e, "variance")
return builtin("variance")(c)
def var_samp(e: ColumnOrName) -> Column:
"""Returns the sample variance of non-NULL records in a group. If all records
inside a group are NULL, a NULL is returned. For a single row, NULL is returned as sample variance.
Alias of :func:`variance`
Example::
>>> df = session.create_dataframe([1, -1, 1, -1, -1], schema=["a"])
>>> df.select(var_samp(col("a"))).collect()
[Row(VARIANCE("A")=Decimal('1.200000'))]
>>> df = session.create_dataframe([1, None, 2, 3, None, 5, 6], schema=["a"])
>>> df.select(var_samp(col("a"))).collect()
[Row(VARIANCE("A")=Decimal('4.300000'))]
>>> df = session.create_dataframe([None, None, None], schema=["a"])
>>> df.select(var_samp(col("a"))).collect()
[Row(VARIANCE("A")=None)]
>>> df = session.create_dataframe([42], schema=["a"])
>>> df.select(var_samp(col("a"))).collect()
[Row(VARIANCE("A")=None)]
"""
c = _to_col_if_str(e, "var_samp")
return variance(c)
def var_pop(e: ColumnOrName) -> Column:
"""Returns the population variance of non-NULL records in a group. If all records
inside a group are NULL, a NULL is returned. The population variance of a single row is 0.0.
Example::
>>> df = session.create_dataframe([1, -1, 1, -1, -1], schema=["a"])
>>> df.select(var_pop(col("a"))).collect()
[Row(VAR_POP("A")=Decimal('0.960000'))]
>>> df = session.create_dataframe([1, None, 2, 3, None, 5, 6], schema=["a"])
>>> df.select(var_pop(col("a"))).collect()
[Row(VAR_POP("A")=Decimal('3.440000'))]
>>> df = session.create_dataframe([None, None, None], schema=["a"])
>>> df.select(var_pop(col("a"))).collect()
[Row(VAR_POP("A")=None)]
>>> df = session.create_dataframe([42], schema=["a"])
>>> df.select(var_pop(col("a"))).collect()
[Row(VAR_POP("A")=Decimal('0.000000'))]
"""
c = _to_col_if_str(e, "var_pop")
return builtin("var_pop")(c)
def approx_percentile(col: ColumnOrName, percentile: float) -> Column:
"""Returns an approximated value for the desired percentile. This function uses the t-Digest algorithm."""
c = _to_col_if_str(col, "approx_percentile")
return builtin("approx_percentile")(c, sql_expr(str(percentile)))
def approx_percentile_accumulate(col: ColumnOrName) -> Column:
"""Returns the internal representation of the t-Digest state (as a JSON object) at the end of aggregation.
This function uses the t-Digest algorithm.
"""
c = _to_col_if_str(col, "approx_percentile_accumulate")
return builtin("approx_percentile_accumulate")(c)
def approx_percentile_estimate(state: ColumnOrName, percentile: float) -> Column:
"""Returns the desired approximated percentile value for the specified t-Digest state.
APPROX_PERCENTILE_ESTIMATE(APPROX_PERCENTILE_ACCUMULATE(.)) is equivalent to
APPROX_PERCENTILE(.).
"""
c = _to_col_if_str(state, "approx_percentile_estimate")
return builtin("approx_percentile_estimate")(c, sql_expr(str(percentile)))
def approx_percentile_combine(state: ColumnOrName) -> Column:
"""Combines (merges) percentile input states into a single output state.
This allows scenarios where APPROX_PERCENTILE_ACCUMULATE is run over horizontal partitions
of the same table, producing an algorithm state for each table partition. These states can
later be combined using APPROX_PERCENTILE_COMBINE, producing the same output state as a
single run of APPROX_PERCENTILE_ACCUMULATE over the entire table.
"""
c = _to_col_if_str(state, "approx_percentile_combine")
return builtin("approx_percentile_combine")(c)
def grouping(*cols: ColumnOrName) -> Column:
"""
Describes which of a list of expressions are grouped in a row produced by a GROUP BY query.
:func:`grouping_id` is an alias of :func:`grouping`.
Example::
>>> from snowflake.snowpark import GroupingSets
>>> df = session.create_dataframe([[1, 2, 3], [4, 5, 6]],schema=["a", "b", "c"])
>>> grouping_sets = GroupingSets([col("a")], [col("b")], [col("a"), col("b")])
>>> df.group_by_grouping_sets(grouping_sets).agg([count("c"), grouping("a"), grouping("b"), grouping("a", "b")]).collect()
[Row(A=1, B=2, COUNT(C)=1, GROUPING(A)=0, GROUPING(B)=0, GROUPING(A, B)=0), \
Row(A=4, B=5, COUNT(C)=1, GROUPING(A)=0, GROUPING(B)=0, GROUPING(A, B)=0), \
Row(A=1, B=None, COUNT(C)=1, GROUPING(A)=0, GROUPING(B)=1, GROUPING(A, B)=1), \
Row(A=4, B=None, COUNT(C)=1, GROUPING(A)=0, GROUPING(B)=1, GROUPING(A, B)=1), \
Row(A=None, B=2, COUNT(C)=1, GROUPING(A)=1, GROUPING(B)=0, GROUPING(A, B)=2), \
Row(A=None, B=5, COUNT(C)=1, GROUPING(A)=1, GROUPING(B)=0, GROUPING(A, B)=2)]
"""
columns = [_to_col_if_str(c, "grouping") for c in cols]
return builtin("grouping")(*columns)
grouping_id = grouping
def coalesce(*e: ColumnOrName) -> Column:
"""Returns the first non-NULL expression among its arguments, or NULL if all its
arguments are NULL.
Example::
>>> df = session.create_dataframe([[1, 2, 3], [None, 2, 3], [None, None, 3], [None, None, None]], schema=['a', 'b', 'c'])
>>> df.select(df.a, df.b, df.c, coalesce(df.a, df.b, df.c).as_("COALESCE")).show()
-----------------------------------
|"A" |"B" |"C" |"COALESCE" |
-----------------------------------
|1 |2 |3 |1 |
|NULL |2 |3 |2 |
|NULL |NULL |3 |3 |
|NULL |NULL |NULL |NULL |
-----------------------------------
<BLANKLINE>
"""
c = [_to_col_if_str(ex, "coalesce") for ex in e]
return builtin("coalesce")(*c)
def equal_nan(e: ColumnOrName) -> Column:
"""
Return true if the value in the column is not a number (NaN).
Example::
>>> import math
>>> df = session.create_dataframe([1.1, math.nan, 2.3], schema=["a"])
>>> df.select(equal_nan(df["a"]).alias("equal_nan")).collect()
[Row(EQUAL_NAN=False), Row(EQUAL_NAN=True), Row(EQUAL_NAN=False)]
"""
c = _to_col_if_str(e, "equal_nan")
return c.equal_nan()
def is_null(e: ColumnOrName) -> Column:
"""
Return true if the value in the column is null.
Example::
>>> from snowflake.snowpark.functions import is_null
>>> df = session.create_dataframe([1.2, float("nan"), None, 1.0], schema=["a"])
>>> df.select(is_null("a").as_("a")).collect()
[Row(A=False), Row(A=False), Row(A=True), Row(A=False)]
"""
c = _to_col_if_str(e, "is_null")
return c.is_null()
def negate(e: ColumnOrName) -> Column:
"""Returns the negation of the value in the column (equivalent to a unary minus).
Example::
>>> df = session.create_dataframe([[1]], schema=["a"])
>>> df.select(negate(col("a").alias("result"))).show()
------------
|"RESULT" |
------------
|-1 |
------------
<BLANKLINE>
"""
c = _to_col_if_str(e, "negate")
return -c
def not_(e: ColumnOrName) -> Column:
"""Returns the inverse of a boolean expression.
Example::
>>> df = session.create_dataframe([[True]], schema=["a"])
>>> df.select(not_(col("a").alias("result"))).show()
------------
|"RESULT" |
------------
|False |
------------