-
Notifications
You must be signed in to change notification settings - Fork 159
/
expressions.py
3498 lines (2975 loc) · 164 KB
/
expressions.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
from __future__ import annotations
import math
import os
import warnings
from datetime import date, datetime, time, timedelta
from decimal import Decimal
from typing import (
TYPE_CHECKING,
Any,
Callable,
Iterable,
Iterator,
Literal,
TypeVar,
overload,
)
import daft.daft as native
from daft import context
from daft.daft import CountMode, ImageFormat, ImageMode, ResourceRequest, bind_stateful_udfs
from daft.daft import PyExpr as _PyExpr
from daft.daft import col as _col
from daft.daft import date_lit as _date_lit
from daft.daft import decimal_lit as _decimal_lit
from daft.daft import duration_lit as _duration_lit
from daft.daft import list_sort as _list_sort
from daft.daft import lit as _lit
from daft.daft import series_lit as _series_lit
from daft.daft import stateful_udf as _stateful_udf
from daft.daft import stateless_udf as _stateless_udf
from daft.daft import time_lit as _time_lit
from daft.daft import timestamp_lit as _timestamp_lit
from daft.daft import to_struct as _to_struct
from daft.daft import tokenize_decode as _tokenize_decode
from daft.daft import tokenize_encode as _tokenize_encode
from daft.daft import url_download as _url_download
from daft.daft import utf8_count_matches as _utf8_count_matches
from daft.datatype import DataType, TimeUnit
from daft.dependencies import pa
from daft.expressions.testing import expr_structurally_equal
from daft.logical.schema import Field, Schema
from daft.series import Series, item_to_series
if TYPE_CHECKING:
import builtins
from daft.io import IOConfig
from daft.udf import PartialStatefulUDF, PartialStatelessUDF
# This allows Sphinx to correctly work against our "namespaced" accessor functions by overriding @property to
# return a class instance of the namespace instead of a property object.
elif os.getenv("DAFT_SPHINX_BUILD") == "1":
from typing import Any
# when building docs (with Sphinx) we need access to the functions
# associated with the namespaces from the class, as we don't have
# an instance; @sphinx_accessor is a @property that allows this.
NS = TypeVar("NS")
class sphinx_accessor(property):
def __get__( # type: ignore[override]
self,
instance: Any,
cls: type[NS],
) -> NS:
try:
return self.fget(instance if isinstance(instance, cls) else cls) # type: ignore[misc]
except (AttributeError, ImportError):
return self # type: ignore[return-value]
property = sphinx_accessor # type: ignore[misc]
def lit(value: object) -> Expression:
"""Creates an Expression representing a column with every value set to the provided value
Example:
>>> import daft
>>> df = daft.from_pydict({"x": [1, 2, 3]})
>>> df = df.with_column("y", daft.lit(1))
>>> df.show()
╭───────┬───────╮
│ x ┆ y │
│ --- ┆ --- │
│ Int64 ┆ Int32 │
╞═══════╪═══════╡
│ 1 ┆ 1 │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ 2 ┆ 1 │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ 3 ┆ 1 │
╰───────┴───────╯
<BLANKLINE>
(Showing first 3 of 3 rows)
Args:
val: value of column
Returns:
Expression: Expression representing the value provided
"""
if isinstance(value, datetime):
# pyo3 datetime (PyDateTime) is not available when running in abi3 mode, workaround
pa_timestamp = pa.scalar(value)
i64_value = pa_timestamp.cast(pa.int64()).as_py()
time_unit = TimeUnit.from_str(pa_timestamp.type.unit)._timeunit
tz = pa_timestamp.type.tz
lit_value = _timestamp_lit(i64_value, time_unit, tz)
elif isinstance(value, date):
# pyo3 date (PyDate) is not available when running in abi3 mode, workaround
epoch_time = value - date(1970, 1, 1)
lit_value = _date_lit(epoch_time.days)
elif isinstance(value, time):
# pyo3 time (PyTime) is not available when running in abi3 mode, workaround
pa_time = pa.scalar(value)
i64_value = pa_time.cast(pa.int64()).as_py()
time_unit = TimeUnit.from_str(pa.type_for_alias(str(pa_time.type)).unit)._timeunit
lit_value = _time_lit(i64_value, time_unit)
elif isinstance(value, timedelta):
# pyo3 timedelta (PyDelta) is not available when running in abi3 mode, workaround
pa_duration = pa.scalar(value)
i64_value = pa_duration.cast(pa.int64()).as_py()
time_unit = TimeUnit.from_str(pa_duration.type.unit)._timeunit
lit_value = _duration_lit(i64_value, time_unit)
elif isinstance(value, Decimal):
sign, digits, exponent = value.as_tuple()
assert isinstance(exponent, int)
lit_value = _decimal_lit(sign == 1, digits, exponent)
elif isinstance(value, Series):
lit_value = _series_lit(value._series)
else:
lit_value = _lit(value)
return Expression._from_pyexpr(lit_value)
def col(name: str) -> Expression:
"""Creates an Expression referring to the column with the provided name.
See :ref:`Column Wildcards` for details on wildcards.
Example:
>>> import daft
>>> df = daft.from_pydict({"x": [1, 2, 3], "y": [4, 5, 6]})
>>> df = df.select(daft.col("x"))
>>> df.show()
╭───────╮
│ x │
│ --- │
│ Int64 │
╞═══════╡
│ 1 │
├╌╌╌╌╌╌╌┤
│ 2 │
├╌╌╌╌╌╌╌┤
│ 3 │
╰───────╯
<BLANKLINE>
(Showing first 3 of 3 rows)
Args:
name: Name of column
Returns:
Expression: Expression representing the selected column
"""
return Expression._from_pyexpr(_col(name))
def interval(
years: int | None = None,
months: int | None = None,
days: int | None = None,
hours: int | None = None,
minutes: int | None = None,
seconds: int | None = None,
millis: int | None = None,
nanos: int | None = None,
) -> Expression:
"""
Creates an Expression representing an interval.
"""
lit_value = native.interval_lit(
years=years, months=months, days=days, hours=hours, minutes=minutes, seconds=seconds, millis=millis, nanos=nanos
)
return Expression._from_pyexpr(lit_value)
class Expression:
_expr: _PyExpr = None # type: ignore
def __init__(self) -> None:
raise NotImplementedError("We do not support creating a Expression via __init__ ")
@property
def str(self) -> ExpressionStringNamespace:
"""Access methods that work on columns of strings"""
return ExpressionStringNamespace.from_expression(self)
@property
def dt(self) -> ExpressionDatetimeNamespace:
"""Access methods that work on columns of datetimes"""
return ExpressionDatetimeNamespace.from_expression(self)
@property
def embedding(self) -> ExpressionEmbeddingNamespace:
"""Access methods that work on columns of embeddings"""
return ExpressionEmbeddingNamespace.from_expression(self)
@property
def float(self) -> ExpressionFloatNamespace:
"""Access methods that work on columns of floats"""
return ExpressionFloatNamespace.from_expression(self)
@property
def url(self) -> ExpressionUrlNamespace:
"""Access methods that work on columns of URLs"""
return ExpressionUrlNamespace.from_expression(self)
@property
def list(self) -> ExpressionListNamespace:
"""Access methods that work on columns of lists"""
return ExpressionListNamespace.from_expression(self)
@property
def struct(self) -> ExpressionStructNamespace:
"""Access methods that work on columns of structs"""
return ExpressionStructNamespace.from_expression(self)
@property
def map(self) -> ExpressionMapNamespace:
"""Access methods that work on columns of maps"""
return ExpressionMapNamespace.from_expression(self)
@property
def image(self) -> ExpressionImageNamespace:
"""Access methods that work on columns of images"""
return ExpressionImageNamespace.from_expression(self)
@property
def partitioning(self) -> ExpressionPartitioningNamespace:
"""Access methods that support partitioning operators"""
return ExpressionPartitioningNamespace.from_expression(self)
@property
def json(self) -> ExpressionJsonNamespace:
"""Access methods that work on columns of json"""
return ExpressionJsonNamespace.from_expression(self)
@staticmethod
def _from_pyexpr(pyexpr: _PyExpr) -> Expression:
expr = Expression.__new__(Expression)
expr._expr = pyexpr
return expr
@staticmethod
def _to_expression(obj: object) -> Expression:
if isinstance(obj, Expression):
return obj
else:
return lit(obj)
@staticmethod
def stateless_udf(
name: builtins.str,
partial: PartialStatelessUDF,
expressions: builtins.list[Expression],
return_dtype: DataType,
resource_request: ResourceRequest | None,
batch_size: int | None,
) -> Expression:
return Expression._from_pyexpr(
_stateless_udf(
name, partial, [e._expr for e in expressions], return_dtype._dtype, resource_request, batch_size
)
)
@staticmethod
def stateful_udf(
name: builtins.str,
partial: PartialStatefulUDF,
expressions: builtins.list[Expression],
return_dtype: DataType,
resource_request: ResourceRequest | None,
init_args: tuple[tuple[Any, ...], dict[builtins.str, Any]] | None,
batch_size: int | None,
concurrency: int | None,
) -> Expression:
return Expression._from_pyexpr(
_stateful_udf(
name,
partial,
[e._expr for e in expressions],
return_dtype._dtype,
resource_request,
init_args,
batch_size,
concurrency,
)
)
@staticmethod
def to_struct(*inputs: Expression | builtins.str) -> Expression:
"""Converts multiple input expressions or column names into a struct.
Example:
>>> import daft
>>> from daft import col
>>> df = daft.from_pydict({"a": [1, 2, 3], "b": ["a", "b", "c"]})
>>> df.select(daft.to_struct(col("a")*2, col("b"))).show()
╭───────────────────────────╮
│ struct │
│ --- │
│ Struct[a: Int64, b: Utf8] │
╞═══════════════════════════╡
│ {a: 2, │
│ b: a, │
│ } │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ {a: 4, │
│ b: b, │
│ } │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ {a: 6, │
│ b: c, │
│ } │
╰───────────────────────────╯
<BLANKLINE>
(Showing first 3 of 3 rows)
Args:
inputs: Expressions to be converted into struct fields.
Returns:
An expression for a struct column with the input columns as its fields.
"""
pyinputs = []
for x in inputs:
if isinstance(x, Expression):
pyinputs.append(x._expr)
elif isinstance(x, str):
pyinputs.append(col(x)._expr)
else:
raise TypeError("expected Expression or str as input for to_struct")
return Expression._from_pyexpr(_to_struct(pyinputs))
def __bool__(self) -> bool:
raise ValueError(
"Expressions don't have a truth value. "
"If you used Python keywords `and` `not` `or` on an expression, use `&` `~` `|` instead."
)
def __abs__(self) -> Expression:
"""Absolute of a numeric expression (``abs(expr)``)"""
return self.abs()
def abs(self) -> Expression:
"""Absolute of a numeric expression (``expr.abs()``)"""
return Expression._from_pyexpr(native.abs(self._expr))
def __add__(self, other: object) -> Expression:
"""Adds two numeric expressions or concatenates two string expressions (``e1 + e2``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr + expr._expr)
def __radd__(self, other: object) -> Expression:
expr = Expression._to_expression(other)
return Expression._from_pyexpr(expr._expr + self._expr)
def __sub__(self, other: object) -> Expression:
"""Subtracts two numeric expressions (``e1 - e2``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr - expr._expr)
def __rsub__(self, other: object) -> Expression:
expr = Expression._to_expression(other)
return Expression._from_pyexpr(expr._expr - self._expr)
def __mul__(self, other: object) -> Expression:
"""Multiplies two numeric expressions (``e1 * e2``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr * expr._expr)
def __rmul__(self, other: object) -> Expression:
expr = Expression._to_expression(other)
return Expression._from_pyexpr(expr._expr * self._expr)
def __truediv__(self, other: object) -> Expression:
"""True divides two numeric expressions (``e1 / e2``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr / expr._expr)
def __rtruediv__(self, other: object) -> Expression:
expr = Expression._to_expression(other)
return Expression._from_pyexpr(expr._expr / self._expr)
def __mod__(self, other: Expression) -> Expression:
"""Takes the mod of two numeric expressions (``e1 % e2``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr % expr._expr)
def __rmod__(self, other: Expression) -> Expression:
"""Takes the mod of two numeric expressions (``e1 % e2``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(expr._expr % self._expr)
def __and__(self, other: Expression) -> Expression:
"""Takes the logical AND of two boolean expressions, or bitwise AND of two integer expressions (``e1 & e2``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr & expr._expr)
def __rand__(self, other: Expression) -> Expression:
"""Takes the logical reverse AND of two boolean expressions (``e1 & e2``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(expr._expr & self._expr)
def __or__(self, other: Expression) -> Expression:
"""Takes the logical OR of two boolean or integer expressions, or bitwise OR of two integer expressions (``e1 | e2``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr | expr._expr)
def __xor__(self, other: Expression) -> Expression:
"""Takes the logical XOR of two boolean or integer expressions, or bitwise XOR of two integer expressions (``e1 ^ e2``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr ^ expr._expr)
def __ror__(self, other: Expression) -> Expression:
"""Takes the logical reverse OR of two boolean expressions (``e1 | e2``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(expr._expr | self._expr)
def __lt__(self, other: Expression) -> Expression:
"""Compares if an expression is less than another (``e1 < e2``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr < expr._expr)
def __le__(self, other: Expression) -> Expression:
"""Compares if an expression is less than or equal to another (``e1 <= e2``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr <= expr._expr)
def __eq__(self, other: Expression) -> Expression: # type: ignore
"""Compares if an expression is equal to another (``e1 == e2``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr == expr._expr)
def __ne__(self, other: Expression) -> Expression: # type: ignore
"""Compares if an expression is not equal to another (``e1 != e2``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr != expr._expr)
def __gt__(self, other: Expression) -> Expression:
"""Compares if an expression is greater than another (``e1 > e2``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr > expr._expr)
def __ge__(self, other: Expression) -> Expression:
"""Compares if an expression is greater than or equal to another (``e1 >= e2``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr >= expr._expr)
def __lshift__(self, other: Expression) -> Expression:
"""Shifts the bits of an integer expression to the left (``e1 << e2``)
Args:
other: The number of bits to shift the expression to the left
"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr << expr._expr)
def __rshift__(self, other: Expression) -> Expression:
"""Shifts the bits of an integer expression to the right (``e1 >> e2``)
.. NOTE::
For unsigned integers, this expression perform a logical right shift.
For signed integers, this expression perform an arithmetic right shift.
Args:
other: The number of bits to shift the expression to the right
"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr >> expr._expr)
def __invert__(self) -> Expression:
"""Inverts a boolean expression (``~e``)"""
expr = self._expr.__invert__()
return Expression._from_pyexpr(expr)
def __floordiv__(self, other: Expression) -> Expression:
"""Floor divides two numeric expressions (``e1 / e2``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr // expr._expr)
def __rfloordiv__(self, other: object) -> Expression:
"""Reverse floor divides two numeric expressions (``e2 / e1``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(expr._expr // self._expr)
def alias(self, name: builtins.str) -> Expression:
"""Gives the expression a new name, which is its column's name in the DataFrame schema and the name
by which subsequent expressions can refer to the results of this expression.
Example:
>>> import daft
>>> df = daft.from_pydict({"x": [1, 2, 3]})
>>> df = df.select(col("x").alias("y"))
>>> df.show()
╭───────╮
│ y │
│ --- │
│ Int64 │
╞═══════╡
│ 1 │
├╌╌╌╌╌╌╌┤
│ 2 │
├╌╌╌╌╌╌╌┤
│ 3 │
╰───────╯
<BLANKLINE>
(Showing first 3 of 3 rows)
Args:
name: New name for expression
Returns:
Expression: Renamed expression
"""
assert isinstance(name, str)
expr = self._expr.alias(name)
return Expression._from_pyexpr(expr)
def cast(self, dtype: DataType) -> Expression:
"""Casts an expression to the given datatype if possible.
The following combinations of datatype casting is valid:
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| Target → | Null | Boolean | Integers | Floats | Decimal128 | String | Binary | Fixed-size Binary | Image | Fixed-shape Image | Embedding | Tensor | Fixed-shape Tensor | Python | List | Fixed-size List | Struct | Map | Timestamp | Date | Time | Duration |
| Source | | | | | | | | | | | | | | | | | | | | | | |
| ↓ | | | | | | | | | | | | | | | | | | | | | | |
+====================+======+=========+==========+========+============+========+========+===================+=======+===================+===========+========+====================+========+======+=================+========+=====+===========+======+======+==========+
| Null | Y | Y | Y | Y | Y | Y | Y | Y | N | N | Y | N | N | Y | Y | Y | Y | Y | Y | Y | Y | Y |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| Boolean | Y | Y | Y | Y | N | Y | Y | N | N | N | N | N | N | Y | N | N | N | N | N | N | N | N |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| Integers | Y | Y | Y | Y | Y | Y | Y | N | N | N | N | N | N | Y | N | N | N | N | Y | Y | Y | Y |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| Floats | Y | Y | Y | Y | Y | Y | Y | N | N | N | N | N | N | Y | N | M | N | N | Y | Y | Y | Y |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| Decimal128 | Y | N | Y | Y | Y | N | N | N | N | N | N | N | N | Y | N | N | N | N | N | N | N | N |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| String | Y | N | Y | Y | N | Y | Y | N | N | N | N | N | N | Y | N | N | N | N | Y | Y | N | N |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| Binary | Y | N | Y | Y | N | Y | Y | Y | N | N | N | N | N | Y | N | N | N | N | N | N | N | N |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| Fixed-size Binary | Y | N | N | N | N | N | Y | N | N | N | N | N | N | Y | N | N | N | N | N | N | N | N |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| Image | N | N | N | N | N | N | N | N | Y | Y | N | Y | Y | Y | N | N | Y | N | N | N | N | N |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| Fixed-size Image | N | N | N | N | N | N | N | N | Y | Y | N | Y | Y | Y | Y | Y | N | N | N | N | N | N |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| Embedding | Y | N | N | N | N | n | N | N | N | Y | N | Y | Y | Y | Y | Y | N | N | N | N | N | N |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| Tensor | Y | N | N | N | N | N | N | N | Y | Y | N | Y | Y | Y | N | N | Y | N | N | N | N | N |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| Fixed-shape Tensor | N | N | N | N | N | N | N | N | N | Y | N | Y | Y | Y | Y | Y | N | N | N | N | N | N |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| Python | Y | Y | Y | Y | N | Y | Y | Y | Y | Y | Y | Y | Y | Y | Y | Y | Y | N | N | N | N | N |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| List | N | N | N | N | N | N | N | N | N | N | Y | N | N | N | Y | Y | N | Y | N | N | N | N |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| Fixed-size List | N | N | N | N | N | N | N | N | N | Y | N | N | Y | N | Y | Y | N | N | N | N | N | N |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| Struct | N | N | N | N | N | N | N | N | Y | N | N | Y | N | N | N | N | Y | N | N | N | N | N |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| Map | N | N | N | N | N | N | N | N | N | N | Y | N | N | N | Y | Y | N | Y | N | N | N | N |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| Timestamp | Y | N | Y | Y | N | Y | N | N | N | N | N | N | N | Y | N | N | N | N | Y | Y | Y | N |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| Date | Y | N | Y | Y | N | Y | N | N | N | N | N | N | N | Y | N | N | N | N | Y | Y | N | N |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| Time | Y | N | Y | Y | N | Y | N | N | N | N | N | N | N | Y | N | N | N | N | N | N | Y | N |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
| Duration | Y | N | Y | Y | N | N | N | N | N | N | N | N | N | Y | N | N | N | N | N | N | N | N |
+--------------------+------+---------+----------+--------+------------+--------+--------+-------------------+-------+-------------------+-----------+--------+--------------------+--------+------+-----------------+--------+-----+-----------+------+------+----------+
Note:
- Overflowing values will be wrapped, e.g. 256 will be cast to 0 for an unsigned 8-bit integer.
Example:
>>> import daft
>>> df = daft.from_pydict({"float": [1.0, 2.5, None]})
>>> df = df.select(daft.col("float").cast(daft.DataType.int64()))
>>> df.show()
╭───────╮
│ float │
│ --- │
│ Int64 │
╞═══════╡
│ 1 │
├╌╌╌╌╌╌╌┤
│ 2 │
├╌╌╌╌╌╌╌┤
│ None │
╰───────╯
<BLANKLINE>
(Showing first 3 of 3 rows)
Returns:
Expression: Expression with the specified new datatype
"""
assert isinstance(dtype, DataType)
expr = self._expr.cast(dtype._dtype)
return Expression._from_pyexpr(expr)
def ceil(self) -> Expression:
"""The ceiling of a numeric expression (``expr.ceil()``)"""
expr = native.ceil(self._expr)
return Expression._from_pyexpr(expr)
def floor(self) -> Expression:
"""The floor of a numeric expression (``expr.floor()``)"""
expr = native.floor(self._expr)
return Expression._from_pyexpr(expr)
def sign(self) -> Expression:
"""The sign of a numeric expression (``expr.sign()``)"""
expr = native.sign(self._expr)
return Expression._from_pyexpr(expr)
def round(self, decimals: int = 0) -> Expression:
"""The round of a numeric expression (``expr.round(decimals = 0)``)
Args:
decimals: number of decimal places to round to. Defaults to 0.
"""
assert isinstance(decimals, int)
expr = native.round(self._expr, decimals)
return Expression._from_pyexpr(expr)
def sqrt(self) -> Expression:
"""The square root of a numeric expression (``expr.sqrt()``)"""
expr = native.sqrt(self._expr)
return Expression._from_pyexpr(expr)
def cbrt(self) -> Expression:
"""The cube root of a numeric expression (``expr.cbrt()``)"""
return Expression._from_pyexpr(native.cbrt(self._expr))
def sin(self) -> Expression:
"""The elementwise sine of a numeric expression (``expr.sin()``)"""
expr = native.sin(self._expr)
return Expression._from_pyexpr(expr)
def cos(self) -> Expression:
"""The elementwise cosine of a numeric expression (``expr.cos()``)"""
expr = native.cos(self._expr)
return Expression._from_pyexpr(expr)
def tan(self) -> Expression:
"""The elementwise tangent of a numeric expression (``expr.tan()``)"""
expr = native.tan(self._expr)
return Expression._from_pyexpr(expr)
def cot(self) -> Expression:
"""The elementwise cotangent of a numeric expression (``expr.cot()``)"""
expr = native.cot(self._expr)
return Expression._from_pyexpr(expr)
def arcsin(self) -> Expression:
"""The elementwise arc sine of a numeric expression (``expr.arcsin()``)"""
expr = native.arcsin(self._expr)
return Expression._from_pyexpr(expr)
def arccos(self) -> Expression:
"""The elementwise arc cosine of a numeric expression (``expr.arccos()``)"""
expr = native.arccos(self._expr)
return Expression._from_pyexpr(expr)
def arctan(self) -> Expression:
"""The elementwise arc tangent of a numeric expression (``expr.arctan()``)"""
expr = native.arctan(self._expr)
return Expression._from_pyexpr(expr)
def arctan2(self, other: Expression) -> Expression:
"""Calculates the four quadrant arctangent of coordinates (y, x), in radians (``expr_y.arctan2(expr_x)``)
* ``x = 0``, ``y = 0``: ``0``
* ``x >= 0``: ``[-pi/2, pi/2]``
* ``y >= 0``: ``(pi/2, pi]``
* ``y < 0``: ``(-pi, -pi/2)``"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(native.arctan2(self._expr, expr._expr))
def arctanh(self) -> Expression:
"""The elementwise inverse hyperbolic tangent of a numeric expression (``expr.arctanh()``)"""
expr = native.arctanh(self._expr)
return Expression._from_pyexpr(expr)
def arccosh(self) -> Expression:
"""The elementwise inverse hyperbolic cosine of a numeric expression (``expr.arccosh()``)"""
expr = native.arccosh(self._expr)
return Expression._from_pyexpr(expr)
def arcsinh(self) -> Expression:
"""The elementwise inverse hyperbolic sine of a numeric expression (``expr.arcsinh()``)"""
expr = native.arcsinh(self._expr)
return Expression._from_pyexpr(expr)
def radians(self) -> Expression:
"""The elementwise radians of a numeric expression (``expr.radians()``)"""
expr = native.radians(self._expr)
return Expression._from_pyexpr(expr)
def degrees(self) -> Expression:
"""The elementwise degrees of a numeric expression (``expr.degrees()``)"""
expr = native.degrees(self._expr)
return Expression._from_pyexpr(expr)
def log2(self) -> Expression:
"""The elementwise log base 2 of a numeric expression (``expr.log2()``)"""
expr = native.log2(self._expr)
return Expression._from_pyexpr(expr)
def log10(self) -> Expression:
"""The elementwise log base 10 of a numeric expression (``expr.log10()``)"""
expr = native.log10(self._expr)
return Expression._from_pyexpr(expr)
def log(self, base: float = math.e) -> Expression: # type: ignore
"""The elementwise log with given base, of a numeric expression (``expr.log(base = math.e)``)
Args:
base: The base of the logarithm. Defaults to e.
"""
assert isinstance(base, (int, float)), f"base must be an int or float, but {type(base)} was provided."
expr = native.log(self._expr, float(base))
return Expression._from_pyexpr(expr)
def ln(self) -> Expression:
"""The elementwise natural log of a numeric expression (``expr.ln()``)"""
expr = native.ln(self._expr)
return Expression._from_pyexpr(expr)
def exp(self) -> Expression:
"""The e^self of a numeric expression (``expr.exp()``)"""
expr = native.exp(self._expr)
return Expression._from_pyexpr(expr)
def bitwise_and(self, other: Expression) -> Expression:
"""Bitwise AND of two integer expressions (``expr.bitwise_and(other)``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr & expr._expr)
def bitwise_or(self, other: Expression) -> Expression:
"""Bitwise OR of two integer expressions (``expr.bitwise_or(other)``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr | expr._expr)
def bitwise_xor(self, other: Expression) -> Expression:
"""Bitwise XOR of two integer expressions (``expr.bitwise_xor(other)``)"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr ^ expr._expr)
def shift_left(self, other: Expression) -> Expression:
"""Shifts the bits of an integer expression to the left (``expr << other``)
Args:
other: The number of bits to shift the expression to the left
"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr << expr._expr)
def shift_right(self, other: Expression) -> Expression:
"""Shifts the bits of an integer expression to the right (``expr >> other``)
.. NOTE::
For unsigned integers, this expression perform a logical right shift.
For signed integers, this expression perform an arithmetic right shift.
Args:
other: The number of bits to shift the expression to the right
"""
expr = Expression._to_expression(other)
return Expression._from_pyexpr(self._expr >> expr._expr)
def count(self, mode: CountMode = CountMode.Valid) -> Expression:
"""Counts the number of values in the expression.
Args:
mode: whether to count all values, non-null (valid) values, or null values. Defaults to CountMode.Valid.
"""
expr = self._expr.count(mode)
return Expression._from_pyexpr(expr)
def sum(self) -> Expression:
"""Calculates the sum of the values in the expression"""
expr = self._expr.sum()
return Expression._from_pyexpr(expr)
def approx_count_distinct(self) -> Expression:
"""
Calculates the approximate number of non-`NULL` unique values in the expression.
Approximation is performed using the `HyperLogLog <https://en.wikipedia.org/wiki/HyperLogLog>`_ algorithm.
Example:
A global calculation of approximate distinct values in a non-NULL column:
>>> import daft
>>> df = daft.from_pydict({"values": [1, 2, 3, None]})
>>> df = df.agg(
... df["values"].approx_count_distinct().alias("distinct_values"),
... )
>>> df.show()
╭─────────────────╮
│ distinct_values │
│ --- │
│ UInt64 │
╞═════════════════╡
│ 3 │
╰─────────────────╯
<BLANKLINE>
(Showing first 1 of 1 rows)
"""
expr = self._expr.approx_count_distinct()
return Expression._from_pyexpr(expr)
def approx_percentiles(self, percentiles: builtins.float | builtins.list[builtins.float]) -> Expression:
"""Calculates the approximate percentile(s) for a column of numeric values
For numeric columns, we use the `sketches_ddsketch crate <https://docs.rs/sketches-ddsketch/latest/sketches_ddsketch/index.html>`_.
This is a Rust implementation of the paper `DDSketch: A Fast and Fully-Mergeable Quantile Sketch with Relative-Error Guarantees (Masson et al.) <https://arxiv.org/pdf/1908.10693>`_
1. Null values are ignored in the computation of the percentiles
2. If all values are Null then the result will also be Null
3. If ``percentiles`` are supplied as a single float, then the resultant column is a ``Float64`` column
4. If ``percentiles`` is supplied as a list, then the resultant column is a ``FixedSizeList[Float64; N]`` column, where ``N`` is the length of the supplied list.
Example:
A global calculation of approximate percentiles:
>>> import daft
>>> df = daft.from_pydict({"scores": [1, 2, 3, 4, 5, None]})
>>> df = df.agg(
... df["scores"].approx_percentiles(0.5).alias("approx_median_score"),
... df["scores"].approx_percentiles([0.25, 0.5, 0.75]).alias("approx_percentiles_scores"),
... )
>>> df.show()
╭─────────────────────┬────────────────────────────────╮
│ approx_median_score ┆ approx_percentiles_scores │
│ --- ┆ --- │
│ Float64 ┆ FixedSizeList[Float64; 3] │
╞═════════════════════╪════════════════════════════════╡
│ 2.9742334234767163 ┆ [1.993661701417351, 2.9742334… │
╰─────────────────────┴────────────────────────────────╯
<BLANKLINE>
(Showing first 1 of 1 rows)
A grouped calculation of approximate percentiles:
>>> df = daft.from_pydict({"class": ["a", "a", "a", "b", "c"], "scores": [1, 2, 3, 1, None]})
>>> df = df.groupby("class").agg(
... df["scores"].approx_percentiles(0.5).alias("approx_median_score"),
... df["scores"].approx_percentiles([0.25, 0.5, 0.75]).alias("approx_percentiles_scores"),
... )
>>> df.show()
╭───────┬─────────────────────┬────────────────────────────────╮
│ class ┆ approx_median_score ┆ approx_percentiles_scores │
│ --- ┆ --- ┆ --- │
│ Utf8 ┆ Float64 ┆ FixedSizeList[Float64; 3] │
╞═══════╪═════════════════════╪════════════════════════════════╡
│ c ┆ None ┆ None │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ a ┆ 1.993661701417351 ┆ [0.9900000000000001, 1.993661… │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ b ┆ 0.9900000000000001 ┆ [0.9900000000000001, 0.990000… │
╰───────┴─────────────────────┴────────────────────────────────╯
<BLANKLINE>
(Showing first 3 of 3 rows)
Args:
percentiles: the percentile(s) at which to find approximate values at. Can be provided as a single
float or a list of floats.
Returns:
A new expression representing the approximate percentile(s). If `percentiles` was a single float, this will be a new `Float64` expression. If `percentiles` was a list of floats, this will be a new expression with type: `FixedSizeList[Float64, len(percentiles)]`.
"""
expr = self._expr.approx_percentiles(percentiles)
return Expression._from_pyexpr(expr)
def mean(self) -> Expression:
"""Calculates the mean of the values in the expression"""
expr = self._expr.mean()
return Expression._from_pyexpr(expr)
def stddev(self) -> Expression:
"""Calculates the standard deviation of the values in the expression"""
expr = self._expr.stddev()
return Expression._from_pyexpr(expr)
def min(self) -> Expression:
"""Calculates the minimum value in the expression"""
expr = self._expr.min()
return Expression._from_pyexpr(expr)
def max(self) -> Expression:
"""Calculates the maximum value in the expression"""
expr = self._expr.max()
return Expression._from_pyexpr(expr)
def any_value(self, ignore_nulls=False) -> Expression:
"""Returns any value in the expression
Args:
ignore_nulls: whether to ignore null values when selecting the value. Defaults to False.
"""
expr = self._expr.any_value(ignore_nulls)
return Expression._from_pyexpr(expr)
def agg_list(self) -> Expression:
"""Aggregates the values in the expression into a list"""
expr = self._expr.agg_list()
return Expression._from_pyexpr(expr)
def agg_concat(self) -> Expression:
"""Aggregates the values in the expression into a single string by concatenating them"""
expr = self._expr.agg_concat()
return Expression._from_pyexpr(expr)
def _explode(self) -> Expression:
expr = native.explode(self._expr)
return Expression._from_pyexpr(expr)
def if_else(self, if_true: Expression, if_false: Expression) -> Expression:
"""Conditionally choose values between two expressions using the current boolean expression as a condition
Example:
>>> import daft
>>> df = daft.from_pydict({"A": [1, 2, 3], "B": [0, 2, 4]})
>>> df = df.with_column("A_if_bigger_else_B", (df["A"] > df["B"]).if_else(df["A"], df["B"]),)
>>> df.collect()
╭───────┬───────┬────────────────────╮
│ A ┆ B ┆ A_if_bigger_else_B │
│ --- ┆ --- ┆ --- │
│ Int64 ┆ Int64 ┆ Int64 │
╞═══════╪═══════╪════════════════════╡
│ 1 ┆ 0 ┆ 1 │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2 ┆ 2 ┆ 2 │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 3 ┆ 4 ┆ 4 │
╰───────┴───────┴────────────────────╯
<BLANKLINE>
(Showing first 3 of 3 rows)
Args:
if_true (Expression): Values to choose if condition is true
if_false (Expression): Values to choose if condition is false
Returns:
Expression: New expression where values are chosen from `if_true` and `if_false`.
"""
if_true = Expression._to_expression(if_true)
if_false = Expression._to_expression(if_false)
return Expression._from_pyexpr(self._expr.if_else(if_true._expr, if_false._expr))
def apply(self, func: Callable, return_dtype: DataType) -> Expression:
"""Apply a function on each value in a given expression
.. NOTE::
This is just syntactic sugar on top of a UDF and is convenient to use when your function only operates
on a single column, and does not benefit from executing on batches. For either of those other use-cases,
use a UDF instead.
Example:
>>> import daft
>>> df = daft.from_pydict({"x": ["1", "2", "tim"]})
>>> def f(x_val: str) -> int:
... if x_val.isnumeric():
... return int(x_val)
... else:
... return 0
>>> df.with_column("num_x", df['x'].apply(f, return_dtype=daft.DataType.int64())).collect()
╭──────┬───────╮
│ x ┆ num_x │
│ --- ┆ --- │
│ Utf8 ┆ Int64 │
╞══════╪═══════╡
│ 1 ┆ 1 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ 2 ┆ 2 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ tim ┆ 0 │
╰──────┴───────╯
<BLANKLINE>
(Showing first 3 of 3 rows)
Args:
func: Function to run per value of the expression
return_dtype: Return datatype of the function that was ran