-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathfunctions.py
More file actions
6217 lines (4974 loc) · 172 KB
/
Copy pathfunctions.py
File metadata and controls
6217 lines (4974 loc) · 172 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
import warnings
from collections.abc import Callable
from typing import TYPE_CHECKING, Any, LiteralString, Optional, Union, overload
from duckdb import (
CaseExpression,
CoalesceOperator,
ColumnExpression,
ConstantExpression,
Expression,
FunctionExpression,
LambdaExpression,
SQLExpression,
)
if TYPE_CHECKING:
from .dataframe import DataFrame
from ..errors import PySparkTypeError
from ..exception import ContributionsAcceptedError
from . import types as _types
from ._typing import ColumnOrName
from .column import Column, _get_expr
def _invoke_function_over_columns(name: str, *cols: "ColumnOrName") -> Column:
"""Invokes n-ary JVM function identified by name
and wraps the result with :class:`~pyspark.sql.Column`.
""" # noqa: D205
cols = [_to_column_expr(expr) for expr in cols]
return _invoke_function(name, *cols)
def _nan_constant() -> Expression:
"""Create a NaN constant expression.
Note: ConstantExpression(float("nan")) returns NULL instead of NaN because
TransformPythonValue() in the C++ layer has nan_as_null=true by default.
This is intentional for data import scenarios (CSV, Pandas, etc.) where NaN
represents missing data.
For mathematical functions that need to return NaN (not NULL) for out-of-range
inputs per PySpark/IEEE 754 semantics, we use SQLExpression as a workaround.
Returns:
-------
Expression
An expression that evaluates to NaN (not NULL)
"""
return SQLExpression("'NaN'::DOUBLE")
def col(column: str) -> Column: # noqa: D103
return Column(ColumnExpression(column))
def upper(col: "ColumnOrName") -> Column:
"""Converts a string expression to upper case.
.. versionadded:: 1.5.0
.. versionchanged:: 3.4.0
Supports Spark Connect.
Parameters
----------
col : :class:`~pyspark.sql.Column` or str
target column to work on.
Returns:
-------
:class:`~pyspark.sql.Column`
upper case values.
Examples:
--------
>>> df = spark.createDataFrame(["Spark", "PySpark", "Pandas API"], "STRING")
>>> df.select(upper("value")).show()
+------------+
|upper(value)|
+------------+
| SPARK|
| PYSPARK|
| PANDAS API|
+------------+
"""
return _invoke_function_over_columns("upper", col)
def ucase(str: "ColumnOrName") -> Column:
"""Returns `str` with all characters changed to uppercase.
.. versionadded:: 3.5.0
Parameters
----------
str : :class:`~pyspark.sql.Column` or str
Input column or strings.
Examples:
--------
>>> import pyspark.sql.functions as sf
>>> spark.range(1).select(sf.ucase(sf.lit("Spark"))).show()
+------------+
|ucase(Spark)|
+------------+
| SPARK|
+------------+
"""
return upper(str)
def when(condition: "Column", value: Column | str) -> Column: # noqa: D103
if not isinstance(condition, Column):
msg = "condition should be a Column"
raise TypeError(msg)
v = _get_expr(value)
expr = CaseExpression(condition.expr, v)
return Column(expr)
def _inner_expr_or_val(val: Column | str) -> Column | str:
return val.expr if isinstance(val, Column) else val
def struct(*cols: Column) -> Column: # noqa: D103
return Column(FunctionExpression("struct_pack", *[_inner_expr_or_val(x) for x in cols]))
def array(*cols: Union["ColumnOrName", list["ColumnOrName"] | tuple["ColumnOrName", ...]]) -> Column:
r"""Creates a new array column.
.. versionadded:: 1.4.0
.. versionchanged:: 3.4.0
Supports Spark Connect.
Parameters
----------
cols : :class:`~pyspark.sql.Column` or str
column names or :class:`~pyspark.sql.Column`\\s that have
the same data type.
Returns:
-------
:class:`~pyspark.sql.Column`
a column of array type.
Examples:
--------
>>> df = spark.createDataFrame([("Alice", 2), ("Bob", 5)], ("name", "age"))
>>> df.select(array("age", "age").alias("arr")).collect()
[Row(arr=[2, 2]), Row(arr=[5, 5])]
>>> df.select(array([df.age, df.age]).alias("arr")).collect()
[Row(arr=[2, 2]), Row(arr=[5, 5])]
>>> df.select(array("age", "age").alias("col")).printSchema()
root
|-- col: array (nullable = false)
| |-- element: long (containsNull = true)
"""
if len(cols) == 1 and isinstance(cols[0], (list, set)):
cols = cols[0]
return _invoke_function_over_columns("list_value", *cols)
def lit(col: Any) -> Column: # noqa: D103, ANN401
return col if isinstance(col, Column) else Column(ConstantExpression(col))
def _invoke_function(function: str, *arguments) -> Column:
return Column(FunctionExpression(function, *arguments))
def _to_column_expr(col: ColumnOrName) -> Expression:
if isinstance(col, Column):
return col.expr
elif isinstance(col, str):
return ColumnExpression(col)
else:
raise PySparkTypeError(
error_class="NOT_COLUMN_OR_STR",
message_parameters={"arg_name": "col", "arg_type": type(col).__name__},
)
def regexp_replace(str: "ColumnOrName", pattern: str, replacement: str) -> Column:
r"""Replace all substrings of the specified string value that match regexp with rep.
.. versionadded:: 1.5.0
Examples:
--------
>>> df = spark.createDataFrame([("100-200",)], ["str"])
>>> df.select(regexp_replace("str", r"(\d+)", "--").alias("d")).collect()
[Row(d='-----')]
"""
return _invoke_function(
"regexp_replace",
_to_column_expr(str),
ConstantExpression(pattern),
ConstantExpression(replacement),
ConstantExpression("g"),
)
def slice(x: "ColumnOrName", start: Union["ColumnOrName", int], length: Union["ColumnOrName", int]) -> Column:
"""Collection function: returns an array containing all the elements in `x` from index `start`
(array indices start at 1, or from the end if `start` is negative) with the specified `length`.
.. versionadded:: 2.4.0
.. versionchanged:: 3.4.0
Supports Spark Connect.
Parameters
----------
x : :class:`~pyspark.sql.Column` or str
column name or column containing the array to be sliced
start : :class:`~pyspark.sql.Column` or str or int
column name, column, or int containing the starting index
length : :class:`~pyspark.sql.Column` or str or int
column name, column, or int containing the length of the slice
Returns:
-------
:class:`~pyspark.sql.Column`
a column of array type. Subset of array.
Examples:
--------
>>> df = spark.createDataFrame([([1, 2, 3],), ([4, 5],)], ["x"])
>>> df.select(slice(df.x, 2, 2).alias("sliced")).collect()
[Row(sliced=[2, 3]), Row(sliced=[5])]
""" # noqa: D205
start = ConstantExpression(start) if isinstance(start, int) else _to_column_expr(start)
length = ConstantExpression(length) if isinstance(length, int) else _to_column_expr(length)
end = start + length
return _invoke_function("list_slice", _to_column_expr(x), start, end)
def asc_nulls_first(col: "ColumnOrName") -> Column:
"""Returns a sort expression based on the ascending order of the given
column name, and null values return before non-null values.
.. versionadded:: 2.4.0
.. versionchanged:: 3.4.0
Supports Spark Connect.
Parameters
----------
col : :class:`~pyspark.sql.Column` or str
target column to sort by in the ascending order.
Returns:
-------
:class:`~pyspark.sql.Column`
the column specifying the order.
Examples:
--------
>>> df1 = spark.createDataFrame([(1, "Bob"), (0, None), (2, "Alice")], ["age", "name"])
>>> df1.sort(asc_nulls_first(df1.name)).show()
+---+-----+
|age| name|
+---+-----+
| 0| NULL|
| 2|Alice|
| 1| Bob|
+---+-----+
""" # noqa: D205
return asc(col).nulls_first()
def asc_nulls_last(col: "ColumnOrName") -> Column:
"""Returns a sort expression based on the ascending order of the given
column name, and null values appear after non-null values.
.. versionadded:: 2.4.0
.. versionchanged:: 3.4.0
Supports Spark Connect.
Parameters
----------
col : :class:`~pyspark.sql.Column` or str
target column to sort by in the ascending order.
Returns:
-------
:class:`~pyspark.sql.Column`
the column specifying the order.
Examples:
--------
>>> df1 = spark.createDataFrame([(0, None), (1, "Bob"), (2, "Alice")], ["age", "name"])
>>> df1.sort(asc_nulls_last(df1.name)).show()
+---+-----+
|age| name|
+---+-----+
| 2|Alice|
| 1| Bob|
| 0| NULL|
+---+-----+
""" # noqa: D205
return asc(col).nulls_last()
def desc_nulls_first(col: "ColumnOrName") -> Column:
"""Returns a sort expression based on the descending order of the given
column name, and null values appear before non-null values.
.. versionadded:: 2.4.0
.. versionchanged:: 3.4.0
Supports Spark Connect.
Parameters
----------
col : :class:`~pyspark.sql.Column` or str
target column to sort by in the descending order.
Returns:
-------
:class:`~pyspark.sql.Column`
the column specifying the order.
Examples:
--------
>>> df1 = spark.createDataFrame([(0, None), (1, "Bob"), (2, "Alice")], ["age", "name"])
>>> df1.sort(desc_nulls_first(df1.name)).show()
+---+-----+
|age| name|
+---+-----+
| 0| NULL|
| 1| Bob|
| 2|Alice|
+---+-----+
""" # noqa: D205
return desc(col).nulls_first()
def desc_nulls_last(col: "ColumnOrName") -> Column:
"""Returns a sort expression based on the descending order of the given
column name, and null values appear after non-null values.
.. versionadded:: 2.4.0
.. versionchanged:: 3.4.0
Supports Spark Connect.
Parameters
----------
col : :class:`~pyspark.sql.Column` or str
target column to sort by in the descending order.
Returns:
-------
:class:`~pyspark.sql.Column`
the column specifying the order.
Examples:
--------
>>> df1 = spark.createDataFrame([(0, None), (1, "Bob"), (2, "Alice")], ["age", "name"])
>>> df1.sort(desc_nulls_last(df1.name)).show()
+---+-----+
|age| name|
+---+-----+
| 1| Bob|
| 2|Alice|
| 0| NULL|
+---+-----+
""" # noqa: D205
return desc(col).nulls_last()
def left(str: "ColumnOrName", len: "ColumnOrName") -> Column:
"""Returns the leftmost `len`(`len` can be string type) characters from the string `str`,
if `len` is less or equal than 0 the result is an empty string.
.. versionadded:: 3.5.0
Parameters
----------
str : :class:`~pyspark.sql.Column` or str
Input column or strings.
len : :class:`~pyspark.sql.Column` or str
Input column or strings, the leftmost `len`.
Examples:
--------
>>> df = spark.createDataFrame(
... [
... (
... "Spark SQL",
... 3,
... )
... ],
... ["a", "b"],
... )
>>> df.select(left(df.a, df.b).alias("r")).collect()
[Row(r='Spa')]
""" # noqa: D205
len = _to_column_expr(len)
return Column(
CaseExpression(len <= ConstantExpression(0), ConstantExpression("")).otherwise(
FunctionExpression("array_slice", _to_column_expr(str), ConstantExpression(0), len)
)
)
def right(str: "ColumnOrName", len: "ColumnOrName") -> Column:
"""Returns the rightmost `len`(`len` can be string type) characters from the string `str`,
if `len` is less or equal than 0 the result is an empty string.
.. versionadded:: 3.5.0
Parameters
----------
str : :class:`~pyspark.sql.Column` or str
Input column or strings.
len : :class:`~pyspark.sql.Column` or str
Input column or strings, the rightmost `len`.
Examples:
--------
>>> df = spark.createDataFrame(
... [
... (
... "Spark SQL",
... 3,
... )
... ],
... ["a", "b"],
... )
>>> df.select(right(df.a, df.b).alias("r")).collect()
[Row(r='SQL')]
""" # noqa: D205
len = _to_column_expr(len)
return Column(
CaseExpression(len <= ConstantExpression(0), ConstantExpression("")).otherwise(
FunctionExpression("array_slice", _to_column_expr(str), -len, ConstantExpression(-1))
)
)
def levenshtein(left: "ColumnOrName", right: "ColumnOrName", threshold: int | None = None) -> Column:
"""Computes the Levenshtein distance of the two given strings.
.. versionadded:: 1.5.0
.. versionchanged:: 3.4.0
Supports Spark Connect.
Parameters
----------
left : :class:`~pyspark.sql.Column` or str
first column value.
right : :class:`~pyspark.sql.Column` or str
second column value.
threshold : int, optional
if set when the levenshtein distance of the two given strings
less than or equal to a given threshold then return result distance, or -1
.. versionchanged: 3.5.0
Added ``threshold`` argument.
Returns:
-------
:class:`~pyspark.sql.Column`
Levenshtein distance as integer value.
Examples:
--------
>>> df0 = spark.createDataFrame(
... [
... (
... "kitten",
... "sitting",
... )
... ],
... ["l", "r"],
... )
>>> df0.select(levenshtein("l", "r").alias("d")).collect()
[Row(d=3)]
>>> df0.select(levenshtein("l", "r", 2).alias("d")).collect()
[Row(d=-1)]
"""
distance = _invoke_function_over_columns("levenshtein", left, right)
if threshold is None:
return distance
else:
distance = _to_column_expr(distance)
return Column(
CaseExpression(distance <= ConstantExpression(threshold), distance).otherwise(ConstantExpression(-1))
)
def lpad(col: "ColumnOrName", len: int, pad: str) -> Column:
"""Left-pad the string column to width `len` with `pad`.
.. versionadded:: 1.5.0
.. versionchanged:: 3.4.0
Supports Spark Connect.
Parameters
----------
col : :class:`~pyspark.sql.Column` or str
target column to work on.
len : int
length of the final string.
pad : str
chars to prepend.
Returns:
-------
:class:`~pyspark.sql.Column`
left padded result.
Examples:
--------
>>> df = spark.createDataFrame(
... [("abcd",)],
... [
... "s",
... ],
... )
>>> df.select(lpad(df.s, 6, "#").alias("s")).collect()
[Row(s='##abcd')]
"""
return _invoke_function("lpad", _to_column_expr(col), ConstantExpression(len), ConstantExpression(pad))
def rpad(col: "ColumnOrName", len: int, pad: str) -> Column:
"""Right-pad the string column to width `len` with `pad`.
.. versionadded:: 1.5.0
.. versionchanged:: 3.4.0
Supports Spark Connect.
Parameters
----------
col : :class:`~pyspark.sql.Column` or str
target column to work on.
len : int
length of the final string.
pad : str
chars to append.
Returns:
-------
:class:`~pyspark.sql.Column`
right padded result.
Examples:
--------
>>> df = spark.createDataFrame(
... [("abcd",)],
... [
... "s",
... ],
... )
>>> df.select(rpad(df.s, 6, "#").alias("s")).collect()
[Row(s='abcd##')]
"""
return _invoke_function("rpad", _to_column_expr(col), ConstantExpression(len), ConstantExpression(pad))
def ascii(col: "ColumnOrName") -> Column:
"""Computes the numeric value of the first character of the string column.
.. versionadded:: 1.5.0
.. versionchanged:: 3.4.0
Supports Spark Connect.
Parameters
----------
col : :class:`~pyspark.sql.Column` or str
target column to work on.
Returns:
-------
:class:`~pyspark.sql.Column`
numeric value.
Examples:
--------
>>> df = spark.createDataFrame(["Spark", "PySpark", "Pandas API"], "STRING")
>>> df.select(ascii("value")).show()
+------------+
|ascii(value)|
+------------+
| 83|
| 80|
| 80|
+------------+
"""
return _invoke_function_over_columns("ascii", col)
def asin(col: "ColumnOrName") -> Column:
"""Computes inverse sine of the input column.
.. versionadded:: 1.4.0
.. versionchanged:: 3.4.0
Supports Spark Connect.
Parameters
----------
col : :class:`~pyspark.sql.Column` or str
target column to compute on.
Returns:
-------
:class:`~pyspark.sql.Column`
inverse sine of `col`, as if computed by `java.lang.Math.asin()`
Examples:
--------
>>> df = spark.createDataFrame([(0,), (2,)])
>>> df.select(asin(df.schema.fieldNames()[0])).show()
+--------+
|ASIN(_1)|
+--------+
| 0.0|
| NaN|
+--------+
"""
col = _to_column_expr(col)
# asin domain is [-1, 1]; return NaN for out-of-range values per PySpark semantics
return Column(
CaseExpression((col < -1.0) | (col > 1.0), _nan_constant()).otherwise(FunctionExpression("asin", col))
)
def like(str: "ColumnOrName", pattern: "ColumnOrName", escapeChar: Optional["Column"] = None) -> Column:
r"""Returns true if str matches `pattern` with `escape`,
null if any arguments are null, false otherwise.
The default escape character is the '\'.
.. versionadded:: 3.5.0
Parameters
----------
str : :class:`~pyspark.sql.Column` or str
A string.
pattern : :class:`~pyspark.sql.Column` or str
A string. See the DuckDB documentation on like_escape for more information.
escape : :class:`~pyspark.sql.Column`
An character added since Spark 3.0. The default escape character is the '\'.
If an escape character precedes a special symbol or another escape character, the
following character is matched literally. It is invalid to escape any other character.
Examples:
--------
>>> df = spark.createDataFrame([("Spark", "_park")], ["a", "b"])
>>> df.select(like(df.a, df.b).alias("r")).collect()
[Row(r=True)]
>>> df = spark.createDataFrame(
... [("%SystemDrive%/Users/John", "/%SystemDrive/%//Users%")], ["a", "b"]
... )
>>> df.select(like(df.a, df.b, lit("/")).alias("r")).collect()
[Row(r=True)]
""" # noqa: D205
escapeChar = ConstantExpression("\\") if escapeChar is None else _to_column_expr(escapeChar)
return _invoke_function("like_escape", _to_column_expr(str), _to_column_expr(pattern), escapeChar)
def ilike(str: "ColumnOrName", pattern: "ColumnOrName", escapeChar: Optional["Column"] = None) -> Column:
r"""Returns true if str matches `pattern` with `escape` case-insensitively,
null if any arguments are null, false otherwise.
The default escape character is the '\'.
.. versionadded:: 3.5.0
Parameters
----------
str : :class:`~pyspark.sql.Column` or str
A string.
pattern : :class:`~pyspark.sql.Column` or str
A string. See the DuckDB documentation on ilike_escape for more information.
escape : :class:`~pyspark.sql.Column`
An character added since Spark 3.0. The default escape character is the '\'.
If an escape character precedes a special symbol or another escape character, the
following character is matched literally. It is invalid to escape any other character.
Examples:
--------
>>> df = spark.createDataFrame([("Spark", "_park")], ["a", "b"])
>>> df.select(ilike(df.a, df.b).alias("r")).collect()
[Row(r=True)]
>>> df = spark.createDataFrame(
... [("%SystemDrive%/Users/John", "/%SystemDrive/%//Users%")], ["a", "b"]
... )
>>> df.select(ilike(df.a, df.b, lit("/")).alias("r")).collect()
[Row(r=True)]
""" # noqa: D205
escapeChar = ConstantExpression("\\") if escapeChar is None else _to_column_expr(escapeChar)
return _invoke_function("ilike_escape", _to_column_expr(str), _to_column_expr(pattern), escapeChar)
def array_agg(col: "ColumnOrName") -> Column:
"""Aggregate function: returns a list of objects with duplicates.
.. versionadded:: 3.5.0
Parameters
----------
col : :class:`~pyspark.sql.Column` or str
target column to compute on.
Returns:
-------
:class:`~pyspark.sql.Column`
list of objects with duplicates.
Examples:
--------
>>> df = spark.createDataFrame([[1], [1], [2]], ["c"])
>>> df.agg(array_agg("c").alias("r")).collect()
[Row(r=[1, 1, 2])]
"""
return _invoke_function_over_columns("list", col)
def collect_list(col: "ColumnOrName") -> Column:
"""Aggregate function: returns a list of objects with duplicates.
.. versionadded:: 1.6.0
.. versionchanged:: 3.4.0
Supports Spark Connect.
Notes:
-----
The function is non-deterministic because the order of collected results depends
on the order of the rows which may be non-deterministic after a shuffle.
Parameters
----------
col : :class:`~pyspark.sql.Column` or str
target column to compute on.
Returns:
-------
:class:`~pyspark.sql.Column`
list of objects with duplicates.
Examples:
--------
>>> df2 = spark.createDataFrame([(2,), (5,), (5,)], ("age",))
>>> df2.agg(collect_list("age")).collect()
[Row(collect_list(age)=[2, 5, 5])]
"""
return array_agg(col)
def array_append(col: "ColumnOrName", value: Column | str) -> Column:
"""Collection function: returns an array of the elements in col1 along
with the added element in col2 at the last of the array.
.. versionadded:: 3.4.0
Parameters
----------
col : :class:`~pyspark.sql.Column` or str
name of column containing array
value :
a literal value, or a :class:`~pyspark.sql.Column` expression.
Returns:
-------
:class:`~pyspark.sql.Column`
an array of values from first array along with the element.
Notes:
-----
Supports Spark Connect.
Examples:
--------
>>> from pyspark.sql import Row
>>> df = spark.createDataFrame([Row(c1=["b", "a", "c"], c2="c")])
>>> df.select(array_append(df.c1, df.c2)).collect()
[Row(array_append(c1, c2)=['b', 'a', 'c', 'c'])]
>>> df.select(array_append(df.c1, "x")).collect()
[Row(array_append(c1, x)=['b', 'a', 'c', 'x'])]
""" # noqa: D205
return _invoke_function("list_append", _to_column_expr(col), _get_expr(value))
def array_insert(arr: "ColumnOrName", pos: Union["ColumnOrName", int], value: Column | str) -> Column:
"""Collection function: adds an item into a given array at a specified array index.
Array indices start at 1, or start from the end if index is negative.
Index above array size appends the array, or prepends the array if index is negative,
with 'null' elements.
.. versionadded:: 3.4.0
Parameters
----------
arr : :class:`~pyspark.sql.Column` or str
name of column containing an array
pos : :class:`~pyspark.sql.Column` or str or int
name of Numeric type column indicating position of insertion
(starting at index 1, negative position is a start from the back of the array)
value :
a literal value, or a :class:`~pyspark.sql.Column` expression.
Returns:
-------
:class:`~pyspark.sql.Column`
an array of values, including the new specified value
Notes:
-----
Supports Spark Connect.
Examples:
--------
>>> df = spark.createDataFrame(
... [(["a", "b", "c"], 2, "d"), (["c", "b", "a"], -2, "d")], ["data", "pos", "val"]
... )
>>> df.select(array_insert(df.data, df.pos.cast("integer"), df.val).alias("data")).collect()
[Row(data=['a', 'd', 'b', 'c']), Row(data=['c', 'b', 'd', 'a'])]
>>> df.select(array_insert(df.data, 5, "hello").alias("data")).collect()
[Row(data=['a', 'b', 'c', None, 'hello']), Row(data=['c', 'b', 'a', None, 'hello'])]
""" # noqa: D205
pos = _get_expr(pos)
arr = _to_column_expr(arr)
# Depending on if the position is positive or not, we need to interpret it differently.
# This is because negative numbers are relative to the end of the NEW list.
# For example, if it's -2, it's expected that the inserted value is at the second position
# in the NEW list.
pos_is_positive = pos > 0
list_length_plus_1 = FunctionExpression("add", FunctionExpression("len", arr), 1)
# If the position is above the list size plus 1, first extend the list with the
# relevant number of nulls to get the list to the size of (pos - 1).
list_ = CaseExpression(
pos > list_length_plus_1,
FunctionExpression("list_resize", arr, FunctionExpression("subtract", pos, 1)),
).otherwise(
CaseExpression(
(pos < 0) & (FunctionExpression("abs", pos) > list_length_plus_1),
FunctionExpression(
"list_concat",
FunctionExpression(
"list_resize",
FunctionExpression("list_value", None),
FunctionExpression("subtract", FunctionExpression("abs", pos), list_length_plus_1),
),
arr,
),
).otherwise(arr)
)
# We slice the array into two parts, insert the value in between and concatenate the two parts
# together again.
return _invoke_function(
"list_concat",
FunctionExpression(
"list_concat",
# First part of the list
FunctionExpression(
"list_slice",
list_,
1,
CaseExpression(pos_is_positive, FunctionExpression("subtract", pos, 1)).otherwise(pos),
),
# Here we insert the value at the specified position
FunctionExpression("list_value", _get_expr(value)),
),
# The remainder of the list
FunctionExpression(
"list_slice",
list_,
CaseExpression(pos_is_positive, pos).otherwise(FunctionExpression("add", pos, 1)),
-1,
),
)
def array_contains(col: "ColumnOrName", value: Column | str) -> Column:
"""Collection function: returns null if the array is null, true if the array contains the
given value, and false otherwise.
Parameters
----------
col : :class:`~pyspark.sql.Column` or str
name of column containing array
value :
value or column to check for in array
Returns:
-------
:class:`~pyspark.sql.Column`
a column of Boolean type.
Examples:
--------
>>> df = spark.createDataFrame([(["a", "b", "c"],), ([],)], ["data"])
>>> df.select(array_contains(df.data, "a")).collect()
[Row(array_contains(data, a)=True), Row(array_contains(data, a)=False)]
>>> df.select(array_contains(df.data, lit("a"))).collect()
[Row(array_contains(data, a)=True), Row(array_contains(data, a)=False)]
""" # noqa: D205
value = _get_expr(value)
return _invoke_function("array_contains", _to_column_expr(col), value)
def array_distinct(col: "ColumnOrName") -> Column:
"""Collection function: removes duplicate values from the array.
.. versionadded:: 2.4.0
.. versionchanged:: 3.4.0
Supports Spark Connect.
Parameters
----------
col : :class:`~pyspark.sql.Column` or str
name of column or expression
Returns:
-------
:class:`~pyspark.sql.Column`
an array of unique values.
Examples:
--------
>>> df = spark.createDataFrame([([1, 2, 3, 2],), ([4, 5, 5, 4],)], ["data"])
>>> df.select(array_distinct(df.data)).collect()
[Row(array_distinct(data)=[1, 2, 3]), Row(array_distinct(data)=[4, 5])]
"""
return _invoke_function_over_columns("array_distinct", col)
def array_intersect(col1: "ColumnOrName", col2: "ColumnOrName") -> Column:
"""Collection function: returns an array of the elements in the intersection of col1 and col2,
without duplicates.
.. versionadded:: 2.4.0
.. versionchanged:: 3.4.0
Supports Spark Connect.
Parameters
----------
col1 : :class:`~pyspark.sql.Column` or str
name of column containing array
col2 : :class:`~pyspark.sql.Column` or str
name of column containing array
Returns:
-------
:class:`~pyspark.sql.Column`
an array of values in the intersection of two arrays.
Examples:
--------
>>> from pyspark.sql import Row
>>> df = spark.createDataFrame([Row(c1=["b", "a", "c"], c2=["c", "d", "a", "f"])])
>>> df.select(array_intersect(df.c1, df.c2)).collect()
[Row(array_intersect(c1, c2)=['a', 'c'])]
""" # noqa: D205
return _invoke_function_over_columns("array_intersect", col1, col2)
def array_union(col1: "ColumnOrName", col2: "ColumnOrName") -> Column:
"""Collection function: returns an array of the elements in the union of col1 and col2,
without duplicates.
.. versionadded:: 2.4.0
.. versionchanged:: 3.4.0
Supports Spark Connect.
Parameters
----------
col1 : :class:`~pyspark.sql.Column` or str
name of column containing array
col2 : :class:`~pyspark.sql.Column` or str
name of column containing array
Returns:
-------