-
Notifications
You must be signed in to change notification settings - Fork 608
/
Copy pathgeneric.py
2055 lines (1742 loc) · 66.6 KB
/
generic.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 contextlib
from typing import TYPE_CHECKING, Any, Iterable, Literal, Sequence
from public import public
import ibis
import ibis.common.exceptions as com
import ibis.expr.datatypes as dt
from ibis.common.deferred import Deferred
import ibis.expr.operations as ops
from ibis.common.grounds import Singleton
from ibis.expr.types.core import Expr, _binop, _FixedTextJupyterMixin
if TYPE_CHECKING:
import pandas as pd
import pyarrow as pa
import ibis.expr.builders as bl
import ibis.expr.types as ir
from ibis.formats.pyarrow import PyArrowData
@public
class Value(Expr):
"""Base class for a data generating expression having a known type."""
def name(self, name):
"""Rename an expression to `name`.
Parameters
----------
name
The new name of the expression
Returns
-------
Value
`self` with name `name`
Examples
--------
>>> import ibis
>>> t = ibis.table(dict(a="int64"), name="t")
>>> t.a.name("b")
r0 := UnboundTable: t
a int64
b: r0.a
"""
# TODO(kszucs): shouldn't do simplification here, but rather later
# when simplifying the whole operation tree
# the expression's name is idendical to the new one
if self.has_name() and self.get_name() == name:
return self
if isinstance(self.op(), ops.Alias):
# only keep a single alias operation
op = ops.Alias(arg=self.op().arg, name=name)
else:
op = ops.Alias(arg=self, name=name)
return op.to_expr()
# TODO(kszucs): should rename to dtype
def type(self) -> dt.DataType:
"""Return the [DataType](./datatypes.qmd) of `self`."""
return self.op().dtype
def hash(self) -> ir.IntegerValue:
"""Compute an integer hash value.
::: {.callout-note}
## The hashing function used is backend-dependent.
:::
Returns
-------
IntegerValue
The hash value of `self`
Examples
--------
>>> import ibis
>>> ibis.options.interactive = True
>>> ibis.literal("hello").hash() # doctest: +SKIP
-4155090522938856779
"""
return ops.Hash(self).to_expr()
def cast(self, target_type: Any) -> Value:
"""Cast expression to indicated data type.
Similar to `pandas.Series.astype`.
Parameters
----------
target_type
Type to cast to. Anything accepted by [`ibis.dtype()`](./datatypes.qmd#ibis.dtype)
Returns
-------
Value
Casted expression
See Also
--------
[`Value.try_cast()`](./expression-generic.qmd#ibis.expr.types.generic.Value.try_cast)
[`ibis.dtype()`](./datatypes.qmd#ibis.dtype)
Examples
--------
>>> import ibis
>>> ibis.options.interactive = True
>>> x = ibis.examples.penguins.fetch()["bill_depth_mm"]
>>> x
┏━━━━━━━━━━━━━━━┓
┃ bill_depth_mm ┃
┡━━━━━━━━━━━━━━━┩
│ float64 │
├───────────────┤
│ 18.7 │
│ 17.4 │
│ 18.0 │
│ NULL │
│ 19.3 │
│ 20.6 │
│ 17.8 │
│ 19.6 │
│ 18.1 │
│ 20.2 │
│ … │
└───────────────┘
python's built-in types can be used
>>> x.cast(int)
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Cast(bill_depth_mm, int64) ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ int64 │
├────────────────────────────┤
│ 19 │
│ 17 │
│ 18 │
│ NULL │
│ 19 │
│ 21 │
│ 18 │
│ 20 │
│ 18 │
│ 20 │
│ … │
└────────────────────────────┘
or string names
>>> x.cast("uint16")
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Cast(bill_depth_mm, uint16) ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ uint16 │
├─────────────────────────────┤
│ 19 │
│ 17 │
│ 18 │
│ NULL │
│ 19 │
│ 21 │
│ 18 │
│ 20 │
│ 18 │
│ 20 │
│ … │
└─────────────────────────────┘
If you make an illegal cast, you won't know until the backend actually
executes it. Consider [`.try_cast()`](#ibis.expr.types.generic.Value.try_cast).
>>> ibis.literal("a string").cast("int64") # doctest: +SKIP
<error>
"""
op = ops.Cast(self, to=target_type)
if op.to == self.type():
# noop case if passed type is the same
return self
if op.to.is_geospatial():
from_geotype = self.type().geotype or "geometry"
to_geotype = op.to.geotype
if from_geotype == to_geotype:
return self
return op.to_expr()
def try_cast(self, target_type: Any) -> Value:
"""Try cast expression to indicated data type.
If the cast fails for a row, the value is returned
as null or NaN depending on target_type and backend behavior.
Parameters
----------
target_type
Type to try cast to. Anything accepted by [`ibis.dtype()`](./datatypes.qmd#ibis.dtype)
Returns
-------
Value
Casted expression
See Also
--------
[`Value.cast()`](./expression-generic.qmd#ibis.expr.types.generic.Value.cast)
[`ibis.dtype()`](./datatypes.qmd#ibis.dtype)
Examples
--------
>>> import ibis
>>> from ibis import _
>>> ibis.options.interactive = True
>>> t = ibis.memtable(
... {"numbers": [1, 2, 3, 4], "strings": ["1.0", "2", "hello", "world"]}
... )
>>> t
┏━━━━━━━━━┳━━━━━━━━━┓
┃ numbers ┃ strings ┃
┡━━━━━━━━━╇━━━━━━━━━┩
│ int64 │ string │
├─────────┼─────────┤
│ 1 │ 1.0 │
│ 2 │ 2 │
│ 3 │ hello │
│ 4 │ world │
└─────────┴─────────┘
>>> t = t.mutate(numbers_to_strings=_.numbers.try_cast("string"))
>>> t = t.mutate(strings_to_numbers=_.strings.try_cast("int"))
>>> t
┏━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━┓
┃ numbers ┃ strings ┃ numbers_to_strings ┃ strings_to_numbers ┃
┡━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━┩
│ int64 │ string │ string │ int64 │
├─────────┼─────────┼────────────────────┼────────────────────┤
│ 1 │ 1.0 │ 1 │ 1 │
│ 2 │ 2 │ 2 │ 2 │
│ 3 │ hello │ 3 │ NULL │
│ 4 │ world │ 4 │ NULL │
└─────────┴─────────┴────────────────────┴────────────────────┘
"""
op = ops.TryCast(self, to=target_type)
if op.to == self.type():
# noop case if passed type is the same
return self
return op.to_expr()
def coalesce(self, *args: Value) -> Value:
"""Return the first non-null value from `args`.
Parameters
----------
args
Arguments from which to choose the first non-null value
Returns
-------
Value
Coalesced expression
See Also
--------
[`ibis.coalesce()`](./expression-generic.qmd#ibis.coalesce)
[`Value.fillna()`](./expression-generic.qmd#ibis.expr.types.generic.Value.fillna)
Examples
--------
>>> import ibis
>>> ibis.coalesce(None, 4, 5).name("x")
x: Coalesce(...)
"""
return ops.Coalesce((self, *args)).to_expr()
def greatest(self, *args: ir.Value) -> ir.Value:
"""Compute the largest value among the supplied arguments.
Parameters
----------
args
Arguments to choose from
Returns
-------
Value
Maximum of the passed arguments
"""
return ops.Greatest((self, *args)).to_expr()
def least(self, *args: ir.Value) -> ir.Value:
"""Compute the smallest value among the supplied arguments.
Parameters
----------
args
Arguments to choose from
Returns
-------
Value
Minimum of the passed arguments
"""
return ops.Least((self, *args)).to_expr()
def typeof(self) -> ir.StringValue:
"""Return the string name of the datatype of self.
The values of the returned strings are necessarily backend dependent.
e.g. duckdb may say "DOUBLE", while sqlite may say "real".
Returns
-------
StringValue
A string indicating the type of the value
Examples
--------
>>> import ibis
>>> ibis.options.interactive = True
>>> vals = ibis.examples.penguins.fetch().head(5).bill_length_mm
>>> vals
┏━━━━━━━━━━━━━━━━┓
┃ bill_length_mm ┃
┡━━━━━━━━━━━━━━━━┩
│ float64 │
├────────────────┤
│ 39.1 │
│ 39.5 │
│ 40.3 │
│ NULL │
│ 36.7 │
└────────────────┘
>>> vals.typeof()
┏━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ TypeOf(bill_length_mm) ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━┩
│ string │
├────────────────────────┤
│ DOUBLE │
│ DOUBLE │
│ DOUBLE │
│ DOUBLE │
│ DOUBLE │
└────────────────────────┘
Different backends have different names for their native types
>>> ibis.duckdb.connect().execute(ibis.literal(5.4).typeof())
'DOUBLE'
>>> ibis.sqlite.connect().execute(ibis.literal(5.4).typeof())
'real'
"""
return ops.TypeOf(self).to_expr()
def fillna(self, fill_value: Scalar) -> Value:
"""Replace any null values with the indicated fill value.
Parameters
----------
fill_value
Value with which to replace `NA` values in `self`
See Also
--------
[`Value.coalesce()`](./expression-generic.qmd#ibis.expr.types.generic.Value.coalesce)
[`ibis.coalesce()`](./expression-generic.qmd#ibis.coalesce)
Examples
--------
>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.examples.penguins.fetch().limit(5)
>>> t.sex
┏━━━━━━━━┓
┃ sex ┃
┡━━━━━━━━┩
│ string │
├────────┤
│ male │
│ female │
│ female │
│ NULL │
│ female │
└────────┘
>>> t.sex.fillna("unrecorded").name("sex")
┏━━━━━━━━━━━━┓
┃ sex ┃
┡━━━━━━━━━━━━┩
│ string │
├────────────┤
│ male │
│ female │
│ female │
│ unrecorded │
│ female │
└────────────┘
Returns
-------
Value
`self` filled with `fill_value` where it is `NA`
"""
return ops.Coalesce((self, fill_value)).to_expr()
def nullif(self, null_if_expr: Value) -> Value:
"""Set values to null if they equal the values `null_if_expr`.
Commonly used to avoid divide-by-zero problems by replacing zero with
`NULL` in the divisor.
Equivalent to `(self == null_if_expr).ifelse(ibis.null(), self)`.
Parameters
----------
null_if_expr
Expression indicating what values should be NULL
Returns
-------
Value
Value expression
Examples
--------
>>> import ibis
>>> ibis.options.interactive = True
>>> vals = ibis.examples.penguins.fetch().head(5).sex
>>> vals
┏━━━━━━━━┓
┃ sex ┃
┡━━━━━━━━┩
│ string │
├────────┤
│ male │
│ female │
│ female │
│ NULL │
│ female │
└────────┘
>>> vals.nullif("male")
┏━━━━━━━━━━━━━━━━━━━━━┓
┃ NullIf(sex, 'male') ┃
┡━━━━━━━━━━━━━━━━━━━━━┩
│ string │
├─────────────────────┤
│ NULL │
│ female │
│ female │
│ NULL │
│ female │
└─────────────────────┘
"""
return ops.NullIf(self, null_if_expr).to_expr()
def between(
self,
lower: Value,
upper: Value,
) -> ir.BooleanValue:
"""Check if this expression is between `lower` and `upper`, inclusive.
Parameters
----------
lower
Lower bound, inclusive
upper
Upper bound, inclusive
Returns
-------
BooleanValue
Expression indicating membership in the provided range
Examples
--------
>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.examples.penguins.fetch().limit(5)
>>> t.bill_length_mm.between(35, 38)
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Between(bill_length_mm, 35, 38) ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ boolean │
├─────────────────────────────────┤
│ False │
│ False │
│ False │
│ NULL │
│ True │
└─────────────────────────────────┘
"""
return ops.Between(self, lower, upper).to_expr()
def isin(self, values: Value | Sequence[Value]) -> ir.BooleanValue:
"""Check whether this expression's values are in `values`.
Parameters
----------
values
Values or expression to check for membership
Returns
-------
BooleanValue
Expression indicating membership
See Also
--------
[`Value.notin()`](./expression-generic.qmd#ibis.expr.types.generic.Value.notin)
Examples
--------
>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.memtable({"a": [1, 2, 3], "b": [2, 3, 4]})
>>> t
┏━━━━━━━┳━━━━━━━┓
┃ a ┃ b ┃
┡━━━━━━━╇━━━━━━━┩
│ int64 │ int64 │
├───────┼───────┤
│ 1 │ 2 │
│ 2 │ 3 │
│ 3 │ 4 │
└───────┴───────┘
Check against a literal sequence of values
>>> t.a.isin([1, 2])
┏━━━━━━━━━━━━━┓
┃ InValues(a) ┃
┡━━━━━━━━━━━━━┩
│ boolean │
├─────────────┤
│ True │
│ True │
│ False │
└─────────────┘
Check against a derived expression
>>> t.a.isin(t.b + 1)
┏━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ InColumn(a, Add(b, 1)) ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━┩
│ boolean │
├────────────────────────┤
│ False │
│ False │
│ True │
└────────────────────────┘
Check against a column from a different table
>>> t2 = ibis.memtable({"x": [99, 2, 99]})
>>> t.a.isin(t2.x)
┏━━━━━━━━━━━━━━━━┓
┃ InColumn(a, x) ┃
┡━━━━━━━━━━━━━━━━┩
│ boolean │
├────────────────┤
│ False │
│ True │
│ False │
└────────────────┘
"""
from ibis.expr.types import ArrayValue
if isinstance(values, ArrayValue):
return ops.ArrayContains(values, self).to_expr()
elif isinstance(values, Column):
return ops.InColumn(self, values).to_expr()
else:
return ops.InValues(self, values).to_expr()
def notin(self, values: Value | Sequence[Value]) -> ir.BooleanValue:
"""Check whether this expression's values are not in `values`.
Opposite of [`Value.isin()`](./expression-generic.qmd#ibis.expr.types.generic.Value.isin).
Parameters
----------
values
Values or expression to check for lack of membership
Returns
-------
BooleanValue
Whether `self`'s values are not contained in `values`
Examples
--------
>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.examples.penguins.fetch().limit(5)
>>> t.bill_depth_mm
┏━━━━━━━━━━━━━━━┓
┃ bill_depth_mm ┃
┡━━━━━━━━━━━━━━━┩
│ float64 │
├───────────────┤
│ 18.7 │
│ 17.4 │
│ 18.0 │
│ NULL │
│ 19.3 │
└───────────────┘
>>> t.bill_depth_mm.notin([18.7, 18.1])
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Not(InValues(bill_depth_mm)) ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ boolean │
├──────────────────────────────┤
│ False │
│ True │
│ True │
│ NULL │
│ True │
└──────────────────────────────┘
"""
return ~self.isin(values)
def substitute(
self,
value: Value | dict,
replacement: Value | None = None,
else_: Value | None = None,
):
"""Replace values given in `values` with `replacement`.
This is similar to the pandas `replace` method.
Parameters
----------
value
Expression or dict.
replacement
If an expression is passed to value, this must be
passed.
else_
If an original value does not match `value`, then `else_` is used.
The default of `None` means leave the original value unchanged.
Returns
-------
Value
Replaced values
Examples
--------
>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.examples.penguins.fetch()
>>> t.island.value_counts().order_by("island")
┏━━━━━━━━━━━┳━━━━━━━━━━━━━━┓
┃ island ┃ island_count ┃
┡━━━━━━━━━━━╇━━━━━━━━━━━━━━┩
│ string │ int64 │
├───────────┼──────────────┤
│ Biscoe │ 168 │
│ Dream │ 124 │
│ Torgersen │ 52 │
└───────────┴──────────────┘
>>> t.island.substitute({"Torgersen": "torg", "Biscoe": "bisc"}).name(
... "island"
... ).value_counts().order_by("island")
┏━━━━━━━━┳━━━━━━━━━━━━━━┓
┃ island ┃ island_count ┃
┡━━━━━━━━╇━━━━━━━━━━━━━━┩
│ string │ int64 │
├────────┼──────────────┤
│ Dream │ 124 │
│ bisc │ 168 │
│ torg │ 52 │
└────────┴──────────────┘
"""
if isinstance(value, dict):
expr = ibis.case()
try:
null_replacement = value.pop(None)
except KeyError:
pass
else:
expr = expr.when(self.isnull(), null_replacement)
for k, v in value.items():
expr = expr.when(self == k, v)
else:
expr = self.case().when(value, replacement)
return expr.else_(else_ if else_ is not None else self).end()
def over(
self,
window=None,
*,
rows=None,
range=None,
group_by=None,
order_by=None,
) -> Value:
"""Construct a window expression.
Parameters
----------
window
Window specification
rows
Whether to use the `ROWS` window clause
range
Whether to use the `RANGE` window clause
group_by
Grouping key
order_by
Ordering key
Returns
-------
Value
A window function expression
"""
import ibis.expr.analysis as an
import ibis.expr.builders as bl
from ibis.common.deferred import Deferred, Call
from ibis import _
if window is None:
window = ibis.window(
rows=rows,
range=range,
group_by=group_by,
order_by=order_by,
)
def bind(table):
frame = window.bind(table)
expr = an.windowize_function(self, frame)
if expr.equals(self):
raise com.IbisTypeError(
"No reduction or analytic function found to construct a window expression"
)
return expr
op = self.op()
if isinstance(op, ops.WindowFunction):
return op.func.to_expr().over(window)
elif isinstance(window, bl.WindowBuilder):
if table := an.find_first_base_table(self.op()):
return bind(table)
else:
return Deferred(Call(bind, _))
else:
raise com.IbisTypeError("Unexpected window type: {window!r}")
def isnull(self) -> ir.BooleanValue:
"""Return whether this expression is NULL.
Examples
--------
>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.examples.penguins.fetch().limit(5)
>>> t.bill_depth_mm
┏━━━━━━━━━━━━━━━┓
┃ bill_depth_mm ┃
┡━━━━━━━━━━━━━━━┩
│ float64 │
├───────────────┤
│ 18.7 │
│ 17.4 │
│ 18.0 │
│ NULL │
│ 19.3 │
└───────────────┘
>>> t.bill_depth_mm.isnull()
┏━━━━━━━━━━━━━━━━━━━━━━━┓
┃ IsNull(bill_depth_mm) ┃
┡━━━━━━━━━━━━━━━━━━━━━━━┩
│ boolean │
├───────────────────────┤
│ False │
│ False │
│ False │
│ True │
│ False │
└───────────────────────┘
"""
return ops.IsNull(self).to_expr()
def notnull(self) -> ir.BooleanValue:
"""Return whether this expression is not NULL.
Examples
--------
>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.examples.penguins.fetch().limit(5)
>>> t.bill_depth_mm
┏━━━━━━━━━━━━━━━┓
┃ bill_depth_mm ┃
┡━━━━━━━━━━━━━━━┩
│ float64 │
├───────────────┤
│ 18.7 │
│ 17.4 │
│ 18.0 │
│ NULL │
│ 19.3 │
└───────────────┘
>>> t.bill_depth_mm.notnull()
┏━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ NotNull(bill_depth_mm) ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━┩
│ boolean │
├────────────────────────┤
│ True │
│ True │
│ True │
│ False │
│ True │
└────────────────────────┘
"""
return ops.NotNull(self).to_expr()
def case(self) -> bl.SimpleCaseBuilder:
"""Create a SimpleCaseBuilder to chain multiple if-else statements.
Add new search expressions with the `.when()` method. These must be
comparable with this column expression. Conclude by calling `.end()`.
Returns
-------
SimpleCaseBuilder
A case builder
See Also
--------
[`Value.substitute()`](./expression-generic.qmd#ibis.expr.types.generic.Value.substitute)
[`ibis.cases()`](./expression-generic.qmd#ibis.expr.types.generic.Value.cases)
[`ibis.case()`](./expression-generic.qmd#ibis.case)
Examples
--------
>>> import ibis
>>> ibis.options.interactive = True
>>> x = ibis.examples.penguins.fetch().head(5)["sex"]
>>> x
┏━━━━━━━━┓
┃ sex ┃
┡━━━━━━━━┩
│ string │
├────────┤
│ male │
│ female │
│ female │
│ NULL │
│ female │
└────────┘
>>> x.case().when("male", "M").when("female", "F").else_("U").end()
┏━━━━━━━━━━━━━━━━━━━━━━┓
┃ SimpleCase(sex, 'U') ┃
┡━━━━━━━━━━━━━━━━━━━━━━┩
│ string │
├──────────────────────┤
│ M │
│ F │
│ F │
│ U │
│ F │
└──────────────────────┘
Cases not given result in the ELSE case
>>> x.case().when("male", "M").else_("OTHER").end()
┏━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ SimpleCase(sex, 'OTHER') ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ string │
├──────────────────────────┤
│ M │
│ OTHER │
│ OTHER │
│ OTHER │
│ OTHER │
└──────────────────────────┘
If you don't supply an ELSE, then NULL is used
>>> x.case().when("male", "M").end()
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ SimpleCase(sex, Cast(None, string)) ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ string │
├─────────────────────────────────────┤
│ M │
│ NULL │
│ NULL │
│ NULL │
│ NULL │
└─────────────────────────────────────┘
"""
import ibis.expr.builders as bl
return bl.SimpleCaseBuilder(self.op())
def cases(
self,
case_result_pairs: Iterable[tuple[ir.BooleanValue, Value]],
default: Value | None = None,
) -> Value:
"""Create a case expression in one shot.
Parameters
----------
case_result_pairs
Conditional-result pairs
default
Value to return if none of the case conditions are true
Returns
-------
Value
Value expression
See Also
--------
[`Value.substitute()`](./expression-generic.qmd#ibis.expr.types.generic.Value.substitute)
[`ibis.cases()`](./expression-generic.qmd#ibis.expr.types.generic.Value.cases)
[`ibis.case()`](./expression-generic.qmd#ibis.case)
Examples
--------
>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.memtable({"values": [1, 2, 1, 2, 3, 2, 4]})
>>> t
┏━━━━━━━━┓
┃ values ┃
┡━━━━━━━━┩
│ int64 │
├────────┤
│ 1 │
│ 2 │
│ 1 │
│ 2 │
│ 3 │
│ 2 │
│ 4 │
└────────┘
>>> number_letter_map = ((1, "a"), (2, "b"), (3, "c"))
>>> t.values.cases(number_letter_map, default="unk").name("replace")
┏━━━━━━━━━┓
┃ replace ┃
┡━━━━━━━━━┩
│ string │
├─────────┤
│ a │
│ b │
│ a │
│ b │
│ c │
│ b │
│ unk │
└─────────┘
"""
builder = self.case()
for case, result in case_result_pairs:
builder = builder.when(case, result)
return builder.else_(default).end()
def collect(self, where: ir.BooleanValue | None = None) -> ir.ArrayScalar:
"""Aggregate this expression's elements into an array.
This function is called `array_agg`, `list_agg`, or `list` in other systems.
Parameters
----------
where
Filter to apply before aggregation
Returns
-------
ArrayScalar
Collected array
Examples
--------
Basic collect usage
>>> import ibis
>>> ibis.options.interactive = True