-
Notifications
You must be signed in to change notification settings - Fork 584
/
relations.py
4686 lines (4159 loc) · 253 KB
/
relations.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 itertools
import operator
import re
from collections import deque
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from keyword import iskeyword
from typing import TYPE_CHECKING, Any, Literal
import toolz
from public import public
import ibis
import ibis.common.exceptions as com
import ibis.expr.datatypes as dt
import ibis.expr.operations as ops
import ibis.expr.schema as sch
from ibis import util
from ibis.common.deferred import Deferred, Resolver
from ibis.expr.rewrites import DerefMap
from ibis.expr.types.core import Expr, _FixedTextJupyterMixin
from ibis.expr.types.generic import Value, literal
from ibis.expr.types.pretty import to_rich
from ibis.selectors import Selector
from ibis.util import deprecated
if TYPE_CHECKING:
import pandas as pd
import polars as pl
import pyarrow as pa
from rich.table import Table as RichTable
import ibis.expr.types as ir
import ibis.selectors as s
from ibis.expr.operations.relations import JoinKind, Set
from ibis.expr.schema import SchemaLike
from ibis.expr.types import Table
from ibis.expr.types.groupby import GroupedTable
from ibis.expr.types.temporal_windows import WindowedTable
from ibis.formats.pyarrow import PyArrowData
from ibis.selectors import IfAnyAll
def _regular_join_method(
name: str,
how: Literal[
"inner",
"left",
"outer",
"right",
"semi",
"anti",
"any_inner",
"any_left",
],
):
def f( # noqa: D417
self: ir.Table,
right: ir.Table,
predicates: str
| Sequence[
str | tuple[str | ir.Column, str | ir.Column] | ir.BooleanValue
] = (),
*,
lname: str = "",
rname: str = "{name}_right",
) -> ir.Table:
"""Perform a join between two tables.
Parameters
----------
right
Right table to join
predicates
Boolean or column names to join on
lname
A format string to use to rename overlapping columns in the left
table (e.g. ``"left_{name}"``).
rname
A format string to use to rename overlapping columns in the right
table (e.g. ``"right_{name}"``).
Returns
-------
Table
Joined table
"""
return self.join(right, predicates, how=how, lname=lname, rname=rname)
f.__name__ = name
return f
def bind(table: Table, value) -> Iterator[ir.Value]:
"""Bind a value to a table expression."""
if isinstance(value, str):
# TODO(kszucs): perhaps use getattr(table, value) instead for nicer error msg
yield ops.Field(table, value).to_expr()
elif isinstance(value, ops.Value):
yield value.to_expr()
elif isinstance(value, Value):
yield value
elif isinstance(value, Table):
for name in value.columns:
yield ops.Field(value, name).to_expr()
elif isinstance(value, Deferred):
yield value.resolve(table)
elif isinstance(value, Resolver):
yield value.resolve({"_": table})
elif isinstance(value, Selector):
yield from value.expand(table)
elif callable(value):
# rebind, otherwise the callable is required to return an expression
# which would preclude support for expressions like lambda _: 2
yield from bind(table, value(table))
else:
yield literal(value)
def unwrap_aliases(values: Iterator[ir.Value]) -> Mapping[str, ir.Value]:
"""Unwrap aliases into a mapping of {name: expression}."""
result = {}
for value in values:
node = value.op()
if node.name in result:
raise com.IbisInputError(
f"Duplicate column name {node.name!r} in result set"
)
if isinstance(node, ops.Alias):
result[node.name] = node.arg
else:
result[node.name] = node
return result
@public
class Table(Expr, _FixedTextJupyterMixin):
"""An immutable and lazy dataframe.
Analogous to a SQL table or a pandas DataFrame. A table expression contains
an [ordered set of named columns](./schemas.qmd#ibis.expr.schema.Schema),
each with a single known type. Unless explicitly ordered with an
[`.order_by()`](./expression-tables.qmd#ibis.expr.types.relations.Table.order_by),
the order of rows is undefined.
Table immutability means that the data underlying an Ibis `Table` cannot be modified: every
method on a Table returns a new Table with those changes. Laziness
means that an Ibis `Table` expression does not run your computation every time you call one of its methods.
Instead, it is a symbolic expression that represents a set of operations
to be performed, which typically is translated into a SQL query. That
SQL query is then executed on a backend, where the data actually lives.
The result (now small enough to be manageable) can then be materialized back
into python as a pandas/pyarrow/python DataFrame/Column/scalar.
You will not create Table objects directly. Instead, you will create one
- from a pandas DataFrame, pyarrow table, Polars table, or raw python dicts/lists
with [`ibis.memtable(df)`](./expression-tables.qmd#ibis.memtable)
- from an existing table in a data platform with
[`connection.table("name")`](./expression-tables.qmd#ibis.backends.duckdb.Backend.table)
- from a file or URL, into a specific backend with
[`connection.read_csv/parquet/json("path/to/file")`](../backends/duckdb.qmd#ibis.backends.duckdb.Backend.read_csv)
(only some backends, typically local ones, support this)
- from a file or URL, into the default backend with
[`ibis.read_csv/read_json/read_parquet("path/to/file")`](./expression-tables.qmd#ibis.read_csv)
See the [user guide](https://ibis-project.org/how-to/input-output/basics) for more
info.
"""
# Higher than numpy & dask objects
__array_priority__ = 20
__array_ufunc__ = None
def get_name(self) -> str:
"""Return the fully qualified name of the table."""
arg = self._arg
namespace = getattr(arg, "namespace", ops.Namespace())
pieces = namespace.catalog, namespace.database, arg.name
return ".".join(filter(None, pieces))
def __array__(self, dtype=None):
return self.execute().__array__(dtype)
def __dataframe__(self, nan_as_null: bool = False, allow_copy: bool = True):
from ibis.expr.types.dataframe_interchange import IbisDataFrame
return IbisDataFrame(self, nan_as_null=nan_as_null, allow_copy=allow_copy)
def __arrow_c_stream__(self, requested_schema: object | None = None) -> object:
return self.to_pyarrow().__arrow_c_stream__(requested_schema)
def __pyarrow_result__(
self, table: pa.Table, data_mapper: type[PyArrowData] | None = None
) -> pa.Table:
if data_mapper is None:
from ibis.formats.pyarrow import PyArrowData as data_mapper
return data_mapper.convert_table(table, self.schema())
def __pandas_result__(
self, df: pd.DataFrame, schema: sch.Schema | None = None
) -> pd.DataFrame:
from ibis.formats.pandas import PandasData
return PandasData.convert_table(df, self.schema() if schema is None else schema)
def __polars_result__(self, df: pl.DataFrame) -> Any:
from ibis.formats.polars import PolarsData
return PolarsData.convert_table(df, self.schema())
def bind(self, *args, **kwargs):
# allow the first argument to be either a dictionary or a list of values
if len(args) == 1:
if isinstance(args[0], dict):
kwargs = {**args[0], **kwargs}
args = ()
else:
args = util.promote_list(args[0])
# bind positional arguments
values = []
for arg in args:
values.extend(bind(self, arg))
# bind keyword arguments where each entry can produce only one value
# which is then named with the given key
for key, arg in kwargs.items():
bindings = tuple(bind(self, arg))
if len(bindings) != 1:
raise com.IbisInputError(
"Keyword arguments cannot produce more than one value"
)
(value,) = bindings
values.append(value.name(key))
# dereference the values to `self`
dm = DerefMap.from_targets(self.op())
result = []
for original in values:
value = dm.dereference(original.op()).to_expr()
value = value.name(original.get_name())
result.append(value)
return tuple(result)
def as_scalar(self) -> ir.ScalarExpr:
"""Inform ibis that the table expression should be treated as a scalar.
Note that the table must have exactly one column and one row for this to
work. If the table has more than one column an error will be raised in
expression construction time. If the table has more than one row an
error will be raised by the backend when the expression is executed.
Returns
-------
Scalar
A scalar subquery
Examples
--------
>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.examples.penguins.fetch()
>>> heavy_gentoo = t.filter(t.species == "Gentoo", t.body_mass_g > 6200)
>>> from_that_island = t.filter(t.island == heavy_gentoo.select("island").as_scalar())
>>> from_that_island.species.value_counts().order_by("species")
┏━━━━━━━━━┳━━━━━━━━━━━━━━━┓
┃ species ┃ species_count ┃
┡━━━━━━━━━╇━━━━━━━━━━━━━━━┩
│ string │ int64 │
├─────────┼───────────────┤
│ Adelie │ 44 │
│ Gentoo │ 124 │
└─────────┴───────────────┘
"""
return ops.ScalarSubquery(self).to_expr()
def as_table(self) -> Table:
"""Promote the expression to a table.
This method is a no-op for table expressions.
Returns
-------
Table
A table expression
Examples
--------
>>> t = ibis.table(dict(a="int"), name="t")
>>> s = t.as_table()
>>> t is s
True
"""
return self
def __contains__(self, name: str) -> bool:
"""Return whether `name` is a column in the table.
Parameters
----------
name
Possible column name
Returns
-------
bool
Whether `name` is a column in `self`
Examples
--------
>>> t = ibis.table(dict(a="string", b="float"), name="t")
>>> "a" in t
True
>>> "c" in t
False
"""
return name in self.schema()
def cast(self, schema: SchemaLike) -> Table:
"""Cast the columns of a table.
Similar to `pandas.DataFrame.astype`.
::: {.callout-note}
## If you need to cast columns to a single type, use [selectors](./selectors.qmd).
:::
Parameters
----------
schema
Mapping, schema or iterable of pairs to use for casting
Returns
-------
Table
Casted table
Examples
--------
>>> import ibis
>>> import ibis.selectors as s
>>> ibis.options.interactive = True
>>> t = ibis.examples.penguins.fetch()
>>> t.schema()
ibis.Schema {
species string
island string
bill_length_mm float64
bill_depth_mm float64
flipper_length_mm int64
body_mass_g int64
sex string
year int64
}
>>> cols = ["body_mass_g", "bill_length_mm"]
>>> t[cols].head()
┏━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┓
┃ body_mass_g ┃ bill_length_mm ┃
┡━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━┩
│ int64 │ float64 │
├─────────────┼────────────────┤
│ 3750 │ 39.1 │
│ 3800 │ 39.5 │
│ 3250 │ 40.3 │
│ NULL │ NULL │
│ 3450 │ 36.7 │
└─────────────┴────────────────┘
Columns not present in the input schema will be passed through unchanged
>>> t.columns
['species', 'island', 'bill_length_mm', 'bill_depth_mm', 'flipper_length_mm', 'body_mass_g', 'sex', 'year']
>>> expr = t.cast({"body_mass_g": "float64", "bill_length_mm": "int"})
>>> expr.select(*cols).head()
┏━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┓
┃ body_mass_g ┃ bill_length_mm ┃
┡━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━┩
│ float64 │ int64 │
├─────────────┼────────────────┤
│ 3750.0 │ 39 │
│ 3800.0 │ 40 │
│ 3250.0 │ 40 │
│ NULL │ NULL │
│ 3450.0 │ 37 │
└─────────────┴────────────────┘
Columns that are in the input `schema` but not in the table raise an error
>>> t.cast({"foo": "string"}) # quartodoc: +EXPECTED_FAILURE
Traceback (most recent call last):
...
ibis.common.exceptions.IbisError: Cast schema has fields that are not in the table: ['foo']
"""
return self._cast(schema, cast_method="cast")
def try_cast(self, schema: SchemaLike) -> Table:
"""Cast the columns of a table.
If the cast fails for a row, the value is returned
as `NULL` or `NaN` depending on backend behavior.
Parameters
----------
schema
Mapping, schema or iterable of pairs to use for casting
Returns
-------
Table
Casted table
Examples
--------
>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.memtable({"a": ["1", "2", "3"], "b": ["2.2", "3.3", "book"]})
>>> t.try_cast({"a": "int", "b": "float"})
┏━━━━━━━┳━━━━━━━━━┓
┃ a ┃ b ┃
┡━━━━━━━╇━━━━━━━━━┩
│ int64 │ float64 │
├───────┼─────────┤
│ 1 │ 2.2 │
│ 2 │ 3.3 │
│ 3 │ NULL │
└───────┴─────────┘
"""
return self._cast(schema, cast_method="try_cast")
def _cast(self, schema: SchemaLike, cast_method: str = "cast") -> Table:
schema = sch.schema(schema)
cols = []
columns = self.columns
if missing_fields := frozenset(schema.names).difference(columns):
raise com.IbisError(
f"Cast schema has fields that are not in the table: {sorted(missing_fields)}"
)
for col in columns:
if (new_type := schema.get(col)) is not None:
new_col = getattr(self[col], cast_method)(new_type).name(col)
else:
new_col = col
cols.append(new_col)
return self.select(*cols)
def preview(
self,
*,
max_rows: int | None = None,
max_columns: int | None = None,
max_length: int | None = None,
max_string: int | None = None,
max_depth: int | None = None,
console_width: int | float | None = None,
) -> RichTable:
"""Return a subset as a Rich Table.
This is an explicit version of what you get when you inspect
this object in interactive mode, except with this version you
can pass formatting options. The options are the same as those exposed
in `ibis.options.interactive`.
Parameters
----------
max_rows
Maximum number of rows to display
max_columns
Maximum number of columns to display
max_length
Maximum length for pretty-printed arrays and maps
max_string
Maximum length for pretty-printed strings
max_depth
Maximum depth for nested data types
console_width
Width of the console in characters. If not specified, the width
will be inferred from the console.
Examples
--------
>>> import ibis
>>> t = ibis.examples.penguins.fetch()
Because the console_width is too small, only 2 columns are shown even though
we specified up to 3.
>>> t.preview(
... max_rows=3,
... max_columns=3,
... max_string=8,
... console_width=30,
... ) # doctest: +SKIP
┏━━━━━━━━━┳━━━━━━━━━━┳━━━┓
┃ species ┃ island ┃ … ┃
┡━━━━━━━━━╇━━━━━━━━━━╇━━━┩
│ string │ string │ … │
├─────────┼──────────┼───┤
│ Adelie │ Torgers… │ … │
│ Adelie │ Torgers… │ … │
│ Adelie │ Torgers… │ … │
│ … │ … │ … │
└─────────┴──────────┴───┘
"""
return to_rich(
self,
max_columns=max_columns,
max_rows=max_rows,
max_length=max_length,
max_string=max_string,
max_depth=max_depth,
console_width=console_width,
)
def __getitem__(self, what):
"""Select items from a table expression.
This method implements square bracket syntax for table expressions,
including various forms of projection and filtering.
Parameters
----------
what
Selection object. This can be a variety of types including strings, ints, lists.
Returns
-------
Table | Column
The return type depends on the input. For a single string or int
input a column is returned, otherwise a table is returned.
Examples
--------
>>> import ibis
>>> import ibis.selectors as s
>>> from ibis import _
>>> ibis.options.interactive = True
>>> t = ibis.examples.penguins.fetch()
>>> t
┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
┃ species ┃ island ┃ bill_length_mm ┃ bill_depth_mm ┃ flipper_length_mm ┃ … ┃
┡━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━┩
│ string │ string │ float64 │ float64 │ int64 │ … │
├─────────┼───────────┼────────────────┼───────────────┼───────────────────┼───┤
│ Adelie │ Torgersen │ 39.1 │ 18.7 │ 181 │ … │
│ Adelie │ Torgersen │ 39.5 │ 17.4 │ 186 │ … │
│ Adelie │ Torgersen │ 40.3 │ 18.0 │ 195 │ … │
│ Adelie │ Torgersen │ NULL │ NULL │ NULL │ … │
│ Adelie │ Torgersen │ 36.7 │ 19.3 │ 193 │ … │
│ Adelie │ Torgersen │ 39.3 │ 20.6 │ 190 │ … │
│ Adelie │ Torgersen │ 38.9 │ 17.8 │ 181 │ … │
│ Adelie │ Torgersen │ 39.2 │ 19.6 │ 195 │ … │
│ Adelie │ Torgersen │ 34.1 │ 18.1 │ 193 │ … │
│ Adelie │ Torgersen │ 42.0 │ 20.2 │ 190 │ … │
│ … │ … │ … │ … │ … │ … │
└─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
Return a column by name
>>> t["island"]
┏━━━━━━━━━━━┓
┃ island ┃
┡━━━━━━━━━━━┩
│ string │
├───────────┤
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ … │
└───────────┘
Return the second column, starting from index 0
>>> t.columns[1]
'island'
>>> t[1]
┏━━━━━━━━━━━┓
┃ island ┃
┡━━━━━━━━━━━┩
│ string │
├───────────┤
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ … │
└───────────┘
Extract a range of rows
>>> t[:2]
┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
┃ species ┃ island ┃ bill_length_mm ┃ bill_depth_mm ┃ flipper_length_mm ┃ … ┃
┡━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━┩
│ string │ string │ float64 │ float64 │ int64 │ … │
├─────────┼───────────┼────────────────┼───────────────┼───────────────────┼───┤
│ Adelie │ Torgersen │ 39.1 │ 18.7 │ 181 │ … │
│ Adelie │ Torgersen │ 39.5 │ 17.4 │ 186 │ … │
└─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
>>> t[:5]
┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
┃ species ┃ island ┃ bill_length_mm ┃ bill_depth_mm ┃ flipper_length_mm ┃ … ┃
┡━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━┩
│ string │ string │ float64 │ float64 │ int64 │ … │
├─────────┼───────────┼────────────────┼───────────────┼───────────────────┼───┤
│ Adelie │ Torgersen │ 39.1 │ 18.7 │ 181 │ … │
│ Adelie │ Torgersen │ 39.5 │ 17.4 │ 186 │ … │
│ Adelie │ Torgersen │ 40.3 │ 18.0 │ 195 │ … │
│ Adelie │ Torgersen │ NULL │ NULL │ NULL │ … │
│ Adelie │ Torgersen │ 36.7 │ 19.3 │ 193 │ … │
└─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
>>> t[2:5]
┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
┃ species ┃ island ┃ bill_length_mm ┃ bill_depth_mm ┃ flipper_length_mm ┃ … ┃
┡━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━┩
│ string │ string │ float64 │ float64 │ int64 │ … │
├─────────┼───────────┼────────────────┼───────────────┼───────────────────┼───┤
│ Adelie │ Torgersen │ 40.3 │ 18.0 │ 195 │ … │
│ Adelie │ Torgersen │ NULL │ NULL │ NULL │ … │
│ Adelie │ Torgersen │ 36.7 │ 19.3 │ 193 │ … │
└─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
Some backends support negative slice indexing
>>> t[-5:] # last 5 rows
┏━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
┃ species ┃ island ┃ bill_length_mm ┃ bill_depth_mm ┃ flipper_length_mm ┃ … ┃
┡━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━┩
│ string │ string │ float64 │ float64 │ int64 │ … │
├───────────┼────────┼────────────────┼───────────────┼───────────────────┼───┤
│ Chinstrap │ Dream │ 55.8 │ 19.8 │ 207 │ … │
│ Chinstrap │ Dream │ 43.5 │ 18.1 │ 202 │ … │
│ Chinstrap │ Dream │ 49.6 │ 18.2 │ 193 │ … │
│ Chinstrap │ Dream │ 50.8 │ 19.0 │ 210 │ … │
│ Chinstrap │ Dream │ 50.2 │ 18.7 │ 198 │ … │
└───────────┴────────┴────────────────┴───────────────┴───────────────────┴───┘
>>> t[-5:-3] # last 5th to 3rd rows
┏━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
┃ species ┃ island ┃ bill_length_mm ┃ bill_depth_mm ┃ flipper_length_mm ┃ … ┃
┡━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━┩
│ string │ string │ float64 │ float64 │ int64 │ … │
├───────────┼────────┼────────────────┼───────────────┼───────────────────┼───┤
│ Chinstrap │ Dream │ 55.8 │ 19.8 │ 207 │ … │
│ Chinstrap │ Dream │ 43.5 │ 18.1 │ 202 │ … │
└───────────┴────────┴────────────────┴───────────────┴───────────────────┴───┘
>>> t[2:-2] # chop off the first two and last two rows
┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
┃ species ┃ island ┃ bill_length_mm ┃ bill_depth_mm ┃ flipper_length_mm ┃ … ┃
┡━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━┩
│ string │ string │ float64 │ float64 │ int64 │ … │
├─────────┼───────────┼────────────────┼───────────────┼───────────────────┼───┤
│ Adelie │ Torgersen │ 40.3 │ 18.0 │ 195 │ … │
│ Adelie │ Torgersen │ NULL │ NULL │ NULL │ … │
│ Adelie │ Torgersen │ 36.7 │ 19.3 │ 193 │ … │
│ Adelie │ Torgersen │ 39.3 │ 20.6 │ 190 │ … │
│ Adelie │ Torgersen │ 38.9 │ 17.8 │ 181 │ … │
│ Adelie │ Torgersen │ 39.2 │ 19.6 │ 195 │ … │
│ Adelie │ Torgersen │ 34.1 │ 18.1 │ 193 │ … │
│ Adelie │ Torgersen │ 42.0 │ 20.2 │ 190 │ … │
│ Adelie │ Torgersen │ 37.8 │ 17.1 │ 186 │ … │
│ Adelie │ Torgersen │ 37.8 │ 17.3 │ 180 │ … │
│ … │ … │ … │ … │ … │ … │
└─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
Select columns
>>> t[["island", "bill_length_mm"]].head()
┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┓
┃ island ┃ bill_length_mm ┃
┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━━┩
│ string │ float64 │
├───────────┼────────────────┤
│ Torgersen │ 39.1 │
│ Torgersen │ 39.5 │
│ Torgersen │ 40.3 │
│ Torgersen │ NULL │
│ Torgersen │ 36.7 │
└───────────┴────────────────┘
>>> t["island", "bill_length_mm"].head()
┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┓
┃ island ┃ bill_length_mm ┃
┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━━┩
│ string │ float64 │
├───────────┼────────────────┤
│ Torgersen │ 39.1 │
│ Torgersen │ 39.5 │
│ Torgersen │ 40.3 │
│ Torgersen │ NULL │
│ Torgersen │ 36.7 │
└───────────┴────────────────┘
>>> t[_.island, _.bill_length_mm].head()
┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┓
┃ island ┃ bill_length_mm ┃
┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━━┩
│ string │ float64 │
├───────────┼────────────────┤
│ Torgersen │ 39.1 │
│ Torgersen │ 39.5 │
│ Torgersen │ 40.3 │
│ Torgersen │ NULL │
│ Torgersen │ 36.7 │
└───────────┴────────────────┘
Filtering
>>> t[t.island.lower() != "torgersen"].head()
┏━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
┃ species ┃ island ┃ bill_length_mm ┃ bill_depth_mm ┃ flipper_length_mm ┃ … ┃
┡━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━┩
│ string │ string │ float64 │ float64 │ int64 │ … │
├─────────┼────────┼────────────────┼───────────────┼───────────────────┼───┤
│ Adelie │ Biscoe │ 37.8 │ 18.3 │ 174 │ … │
│ Adelie │ Biscoe │ 37.7 │ 18.7 │ 180 │ … │
│ Adelie │ Biscoe │ 35.9 │ 19.2 │ 189 │ … │
│ Adelie │ Biscoe │ 38.2 │ 18.1 │ 185 │ … │
│ Adelie │ Biscoe │ 38.8 │ 17.2 │ 180 │ … │
└─────────┴────────┴────────────────┴───────────────┴───────────────────┴───┘
Selectors
>>> t[~s.numeric() | (s.numeric() & ~s.c("year"))].head()
┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
┃ species ┃ island ┃ bill_length_mm ┃ bill_depth_mm ┃ flipper_length_mm ┃ … ┃
┡━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━┩
│ string │ string │ float64 │ float64 │ int64 │ … │
├─────────┼───────────┼────────────────┼───────────────┼───────────────────┼───┤
│ Adelie │ Torgersen │ 39.1 │ 18.7 │ 181 │ … │
│ Adelie │ Torgersen │ 39.5 │ 17.4 │ 186 │ … │
│ Adelie │ Torgersen │ 40.3 │ 18.0 │ 195 │ … │
│ Adelie │ Torgersen │ NULL │ NULL │ NULL │ … │
│ Adelie │ Torgersen │ 36.7 │ 19.3 │ 193 │ … │
└─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
>>> t[s.r["bill_length_mm":"body_mass_g"]].head()
┏━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┓
┃ bill_length_mm ┃ bill_depth_mm ┃ flipper_length_mm ┃ body_mass_g ┃
┡━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━┩
│ float64 │ float64 │ int64 │ int64 │
├────────────────┼───────────────┼───────────────────┼─────────────┤
│ 39.1 │ 18.7 │ 181 │ 3750 │
│ 39.5 │ 17.4 │ 186 │ 3800 │
│ 40.3 │ 18.0 │ 195 │ 3250 │
│ NULL │ NULL │ NULL │ NULL │
│ 36.7 │ 19.3 │ 193 │ 3450 │
└────────────────┴───────────────┴───────────────────┴─────────────┘
"""
from ibis.expr.types.logical import BooleanValue
if isinstance(what, slice):
limit, offset = util.slice_to_limit_offset(what, self.count())
return self.limit(limit, offset=offset)
# skip the self.bind call for single column access with strings or ints
# because dereferencing has significant overhead
elif isinstance(what, str):
return ops.Field(self.op(), what).to_expr()
elif isinstance(what, int):
return ops.Field(self.op(), self.columns[what]).to_expr()
args = [
self.columns[arg] if isinstance(arg, int) else arg
for arg in util.promote_list(what)
]
values = self.bind(args)
if isinstance(what, (str, int)):
assert len(values) == 1
return values[0]
elif util.all_of(values, BooleanValue):
return self.filter(values)
else:
return self.select(values)
def __len__(self):
raise com.ExpressionError("Use .count() instead")
def __getattr__(self, key: str) -> ir.Column:
"""Return the column name of a table.
Parameters
----------
key
Column name
Returns
-------
Column
Column expression with name `key`
Examples
--------
>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.examples.penguins.fetch()
>>> t.island
┏━━━━━━━━━━━┓
┃ island ┃
┡━━━━━━━━━━━┩
│ string │
├───────────┤
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ Torgersen │
│ … │
└───────────┘
"""
try:
return ops.Field(self, key).to_expr()
except com.IbisTypeError:
pass
# A mapping of common attribute typos, mapping them to the proper name
common_typos = {
"sort": "order_by",
"sort_by": "order_by",
"sortby": "order_by",
"orderby": "order_by",
"groupby": "group_by",
}
if key in common_typos:
hint = common_typos[key]
raise AttributeError(
f"{type(self).__name__} object has no attribute {key!r}, did you mean {hint!r}"
)
raise AttributeError(f"'Table' object has no attribute {key!r}")
def __dir__(self) -> list[str]:
out = set(dir(type(self)))
out.update(c for c in self.columns if c.isidentifier() and not iskeyword(c))
return sorted(out)
def _ipython_key_completions_(self) -> list[str]:
return self.columns
@property
def columns(self) -> list[str]:
"""The list of column names in this table.
Examples
--------
>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.examples.penguins.fetch()
>>> t.columns
['species',
'island',
'bill_length_mm',
'bill_depth_mm',
'flipper_length_mm',
'body_mass_g',
'sex',
'year']
"""
return list(self.schema().names)
def schema(self) -> sch.Schema:
"""Return the [Schema](./schemas.qmd#ibis.expr.schema.Schema) for this table.
Returns
-------
Schema
The table's schema.
Examples
--------
>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.examples.penguins.fetch()
>>> t.schema()
ibis.Schema {
species string
island string
bill_length_mm float64
bill_depth_mm float64
flipper_length_mm int64
body_mass_g int64
sex string
year int64
}
"""
return self.op().schema
def group_by(
self,
*by: str | ir.Value | Iterable[str] | Iterable[ir.Value] | None,
**key_exprs: str | ir.Value | Iterable[str] | Iterable[ir.Value],
) -> GroupedTable:
"""Create a grouped table expression.
Similar to SQL's GROUP BY statement, or pandas .groupby() method.
Parameters
----------
by
Grouping expressions
key_exprs
Named grouping expressions
Returns
-------
GroupedTable
A grouped table expression
Examples
--------
>>> import ibis
>>> from ibis import _
>>> ibis.options.interactive = True
>>> t = ibis.memtable(
... {
... "fruit": ["apple", "apple", "banana", "orange"],
... "price": [0.5, 0.5, 0.25, 0.33],
... }
... )
>>> t
┏━━━━━━━━┳━━━━━━━━━┓
┃ fruit ┃ price ┃
┡━━━━━━━━╇━━━━━━━━━┩
│ string │ float64 │
├────────┼─────────┤
│ apple │ 0.50 │
│ apple │ 0.50 │
│ banana │ 0.25 │
│ orange │ 0.33 │
└────────┴─────────┘
>>> t.group_by("fruit").agg(total_cost=_.price.sum(), avg_cost=_.price.mean()).order_by(
... "fruit"
... )
┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━┓
┃ fruit ┃ total_cost ┃ avg_cost ┃
┡━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━┩
│ string │ float64 │ float64 │
├────────┼────────────┼──────────┤
│ apple │ 1.00 │ 0.50 │
│ banana │ 0.25 │ 0.25 │
│ orange │ 0.33 │ 0.33 │
└────────┴────────────┴──────────┘
"""
from ibis.expr.types.groupby import GroupedTable
by = tuple(v for v in by if v is not None)
groups = self.bind(*by, **key_exprs)
return GroupedTable(self, groups)
# TODO(kszucs): shouldn't this be ibis.rowid() instead not bound to a specific table?
def rowid(self) -> ir.IntegerValue:
"""A unique integer per row.
::: {.callout-note}
## This operation is only valid on physical tables
Any further meaning behind this expression is backend dependent.
Generally this corresponds to some index into the database storage
(for example, SQLite and DuckDB's `rowid`).
For a monotonically increasing row number, see `ibis.row_number`.
:::
Returns
-------
IntegerColumn
An integer column
"""
if not isinstance(self.op(), ops.PhysicalTable):
raise com.IbisTypeError(
"rowid() is only valid for physical tables, not for generic "
"table expressions"
)
return ops.RowID(self).to_expr()
def view(self) -> Table:
"""Create a new table expression distinct from the current one.
Use this API for any self-referencing operations like a self-join.