Skip to content

Table Expressions

Table expressions form the basis for most Ibis expressions.

Table

Bases: Expr, _FixedTextJupyterMixin

Source code in ibis/expr/types/relations.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
@public
class Table(Expr, _FixedTextJupyterMixin):
    # Higher than numpy & dask objects
    __array_priority__ = 20

    __array_ufunc__ = None

    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 __pyarrow_result__(self, table: pa.Table) -> pa.Table:
        from ibis.formats.pyarrow import PyArrowData

        return PyArrowData.convert_table(table, self.schema())

    def __pandas_result__(self, df: pd.DataFrame) -> pd.DataFrame:
        from ibis.formats.pandas import PandasData

        return PandasData.convert_table(df, self.schema())

    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: SupportsSchema) -> Table:
        """Cast the columns of a table.

        !!! note "If you need to cast columns to a single type, use [selectors](https://ibis-project.org/blog/selectors/)."

        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 │            nan │
        │        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 │
        │         nan │           NULL │
        │      3450.0 │             37 │
        └─────────────┴────────────────┘

        Columns that are in the input `schema` but not in the table raise an error

        >>> t.cast({"foo": "string"})
        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: SupportsSchema) -> 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 │     nan │
        └───────┴─────────┘
        """
        return self._cast(schema, cast_method="try_cast")

    def _cast(self, schema: SupportsSchema, 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 __rich_console__(self, console, options):
        from rich.text import Text

        from ibis.expr.types.pretty import to_rich_table

        if not ibis.options.interactive:
            return console.render(Text(self._repr()), options=options)

        if console.is_jupyter:
            # Rich infers a console width in jupyter notebooks, but since
            # notebooks can use horizontal scroll bars we don't want to apply a
            # limit here. Since rich requires an integer for max_width, we
            # choose an arbitrarily large integer bound. Note that we need to
            # handle this here rather than in `to_rich_table`, as this setting
            # also needs to be forwarded to `console.render`.
            options = options.update(max_width=1_000_000)
            width = None
        else:
            width = options.max_width

        table = to_rich_table(self, width)
        return console.render(table, options=options)

    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 │            nan │           nan │              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 │            nan │           nan │              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 │            nan │           nan │              NULL │ … │
        │ Adelie  │ Torgersen │           36.7 │          19.3 │               193 │ … │
        └─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘

        Select columns

        >>> t[["island", "bill_length_mm"]].head()
        ┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┓
        ┃ island    ┃ bill_length_mm ┃
        ┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━━┩
        │ string    │ float64        │
        ├───────────┼────────────────┤
        │ Torgersen │           39.1 │
        │ Torgersen │           39.5 │
        │ Torgersen │           40.3 │
        │ Torgersen │            nan │
        │ 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 │            nan │
        │ 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 │            nan │
        │ 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 │            nan │           nan │              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 │
        │            nan │           nan │              NULL │        NULL │
        │           36.7 │          19.3 │               193 │        3450 │
        └────────────────┴───────────────┴───────────────────┴─────────────┘
        """
        from ibis.expr.types.generic import Column
        from ibis.expr.types.logical import BooleanValue

        if isinstance(what, (str, int)):
            return ops.TableColumn(self, what).to_expr()

        if isinstance(what, slice):
            step = what.step
            if step is not None and step != 1:
                raise ValueError('Slice step can only be 1')
            start = what.start or 0
            stop = what.stop

            if stop is None or stop < 0:
                raise ValueError('End index must be a positive number')

            if start < 0:
                raise ValueError('Start index must be a positive number')

            return self.limit(stop - start, offset=start)

        what = bind_expr(self, what)

        if isinstance(what, (list, tuple, Table)):
            # Projection case
            return self.select(what)
        elif isinstance(what, BooleanValue):
            # Boolean predicate
            return self.filter([what])
        elif isinstance(what, Column):
            # Projection convenience
            return self.select(what)
        else:
            raise NotImplementedError(
                'Selection rows or columns with {} objects is not '
                'supported'.format(type(what).__name__)
            )

    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 │
        │ …         │
        └───────────┘
        """
        with contextlib.suppress(com.IbisTypeError):
            return ops.TableColumn(self, key).to_expr()

        # 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

    def _ensure_expr(self, expr):
        import numpy as np

        from ibis.selectors import Selector

        if isinstance(expr, str):
            # treat strings as column names
            return self[expr]
        elif isinstance(expr, (int, np.integer)):
            # treat Python integers as a column index
            return self[self.schema().name_at_position(expr)]
        elif isinstance(expr, Deferred):
            # resolve deferred expressions
            return expr.resolve(self)
        elif isinstance(expr, Selector):
            return expr.expand(self)
        elif callable(expr):
            return expr(self)
        else:
            return expr

    @property
    def columns(self) -> list[str]:
        """The list of columns 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 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 = None,
        **key_exprs: str | ir.Value | Iterable[str] | Iterable[ir.Value],
    ) -> GroupedTable:
        """Create a grouped table expression.

        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())
        ┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━┓
        ┃ 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

        return GroupedTable(self, by, **key_exprs)

    def rowid(self) -> ir.IntegerValue:
        """A unique integer per row.

        !!! 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 or 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.

        Returns
        -------
        Table
            Table expression
        """
        return ops.SelfReference(self).to_expr()

    def difference(self, table: Table, *rest: Table, distinct: bool = True) -> Table:
        """Compute the set difference of multiple table expressions.

        The input tables must have identical schemas.

        Parameters
        ----------
        table:
            A table expression
        *rest:
            Additional table expressions
        distinct
            Only diff distinct rows not occurring in the calling table

        See Also
        --------
        [`ibis.difference`][ibis.difference]

        Returns
        -------
        Table
            The rows present in `self` that are not present in `tables`.

        Examples
        --------
        >>> import ibis
        >>> ibis.options.interactive = True
        >>> t1 = ibis.memtable({"a": [1, 2]})
        >>> t1
        ┏━━━━━━━┓
        ┃ a     ┃
        ┡━━━━━━━┩
        │ int64 │
        ├───────┤
        │     1 │
        │     2 │
        └───────┘
        >>> t2 = ibis.memtable({"a": [2, 3]})
        >>> t2
        ┏━━━━━━━┓
        ┃ a     ┃
        ┡━━━━━━━┩
        │ int64 │
        ├───────┤
        │     2 │
        │     3 │
        └───────┘
        >>> t1.difference(t2)
        ┏━━━━━━━┓
        ┃ a     ┃
        ┡━━━━━━━┩
        │ int64 │
        ├───────┤
        │     1 │
        └───────┘
        """
        node = ops.Difference(self, table, distinct=distinct)
        for table in rest:
            node = ops.Difference(node, table, distinct=distinct)
        return node.to_expr().select(self.columns)

    def aggregate(
        self,
        metrics: Sequence[ir.Scalar] | None = None,
        by: Sequence[ir.Value] | None = None,
        having: Sequence[ir.BooleanValue] | None = None,
        **kwargs: ir.Value,
    ) -> Table:
        """Aggregate a table with a given set of reductions grouping by `by`.

        Parameters
        ----------
        metrics
            Aggregate expressions. These can be any scalar-producing
            expression, including aggregation functions like `sum` or literal
            values like `ibis.literal(1)`.
        by
            Grouping expressions.
        having
            Post-aggregation filters. The shape requirements are the same
            `metrics`, but the output type for `having` is `boolean`.

            !!! warning "Expressions like `x is None` return `bool` and **will not** generate a SQL comparison to `NULL`"
        kwargs
            Named aggregate expressions

        Returns
        -------
        Table
            An aggregate 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.aggregate(by=["fruit"], total_cost=_.price.sum(), avg_cost=_.price.mean(), having=_.price.sum() < 0.5)
        ┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━┓
        ┃ fruit  ┃ total_cost ┃ avg_cost ┃
        ┡━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━┩
        │ string │ float64    │ float64  │
        ├────────┼────────────┼──────────┤
        │ banana │       0.25 │     0.25 │
        │ orange │       0.33 │     0.33 │
        └────────┴────────────┴──────────┘
        """
        import ibis.expr.analysis as an

        metrics = itertools.chain(
            itertools.chain.from_iterable(
                (
                    (_ensure_expr(self, m) for m in metric)
                    if isinstance(metric, (list, tuple))
                    else util.promote_list(_ensure_expr(self, metric))
                )
                for metric in util.promote_list(metrics)
            ),
            (
                e.name(name)
                for name, expr in kwargs.items()
                for e in util.promote_list(_ensure_expr(self, expr))
            ),
        )

        agg = ops.Aggregation(
            self,
            metrics=list(metrics),
            by=bind_expr(self, util.promote_list(by)),
            having=bind_expr(self, util.promote_list(having)),
        )
        agg = an.simplify_aggregation(agg)

        return agg.to_expr()

    agg = aggregate

    def distinct(
        self,
        *,
        on: str | Iterable[str] | s.Selector | None = None,
        keep: Literal["first", "last"] | None = "first",
    ) -> Table:
        """Return a Table with duplicate rows removed.

        Similar to `pandas.DataFrame.drop_duplicates()`.

        !!! note "Some backends do not support `keep='last'`"

        Parameters
        ----------
        on
            Only consider certain columns for identifying duplicates.
            By default deduplicate all of the columns.
        keep
            Determines which duplicates to keep.

            - `"first"`: Drop duplicates except for the first occurrence.
            - `"last"`: Drop duplicates except for the last occurrence.
            - `None`: Drop all duplicates

        Examples
        --------
        >>> import ibis
        >>> import ibis.examples as ex
        >>> import ibis.selectors as s
        >>> ibis.options.interactive = True
        >>> t = ex.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 │            nan │           nan │              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 │ … │
        │ …       │ …         │              … │             … │                 … │ … │
        └─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘

        Compute the distinct rows of a subset of columns

        >>> t[["species", "island"]].distinct()
        ┏━━━━━━━━━━━┳━━━━━━━━━━━┓
        ┃ species   ┃ island    ┃
        ┡━━━━━━━━━━━╇━━━━━━━━━━━┩
        │ string    │ string    │
        ├───────────┼───────────┤
        │ Adelie    │ Torgersen │
        │ Adelie    │ Biscoe    │
        │ Adelie    │ Dream     │
        │ Gentoo    │ Biscoe    │
        │ Chinstrap │ Dream     │
        └───────────┴───────────┘

        Drop all duplicate rows except the first

        >>> t.distinct(on=["species", "island"], keep="first")
        ┏━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━┓
        ┃ species   ┃ island    ┃ bill_length_mm ┃ bill_depth_… ┃ flipper_length_mm ┃  ┃
        ┡━━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━┩
        │ string    │ string    │ float64        │ float64      │ int64             │  │
        ├───────────┼───────────┼────────────────┼──────────────┼───────────────────┼──┤
        │ Adelie    │ Torgersen │           39.1 │         18.7 │               181 │  │
        │ Adelie    │ Biscoe    │           37.8 │         18.3 │               174 │  │
        │ Adelie    │ Dream     │           39.5 │         16.7 │               178 │  │
        │ Gentoo    │ Biscoe    │           46.1 │         13.2 │               211 │  │
        │ Chinstrap │ Dream     │           46.5 │         17.9 │               192 │  │
        └───────────┴───────────┴────────────────┴──────────────┴───────────────────┴──┘

        Drop all duplicate rows except the last

        >>> t.distinct(on=["species", "island"], keep="last")
        ┏━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━┓
        ┃ species   ┃ island    ┃ bill_length_mm ┃ bill_depth_… ┃ flipper_length_mm ┃  ┃
        ┡━━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━┩
        │ string    │ string    │ float64        │ float64      │ int64             │  │
        ├───────────┼───────────┼────────────────┼──────────────┼───────────────────┼──┤
        │ Adelie    │ Torgersen │           43.1 │         19.2 │               197 │  │
        │ Adelie    │ Biscoe    │           42.7 │         18.3 │               196 │  │
        │ Adelie    │ Dream     │           41.5 │         18.5 │               201 │  │
        │ Gentoo    │ Biscoe    │           49.9 │         16.1 │               213 │  │
        │ Chinstrap │ Dream     │           50.2 │         18.7 │               198 │  │
        └───────────┴───────────┴────────────────┴──────────────┴───────────────────┴──┘

        Drop all duplicated rows

        >>> expr = t.distinct(on=["species", "island", "year", "bill_length_mm"], keep=None)
        >>> expr.count()
        273
        >>> t.count()
        344

        You can pass [`selectors`][ibis.selectors] to `on`

        >>> t.distinct(on=~s.numeric())
        ┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
        ┃ 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 │            nan │           nan │              NULL │ … │
        │ Adelie  │ Biscoe    │           37.8 │          18.3 │               174 │ … │
        │ Adelie  │ Biscoe    │           37.7 │          18.7 │               180 │ … │
        │ Adelie  │ Dream     │           39.5 │          16.7 │               178 │ … │
        │ Adelie  │ Dream     │           37.2 │          18.1 │               178 │ … │
        │ Adelie  │ Dream     │           37.5 │          18.9 │               179 │ … │
        │ Gentoo  │ Biscoe    │           46.1 │          13.2 │               211 │ … │
        │ Gentoo  │ Biscoe    │           50.0 │          16.3 │               230 │ … │
        │ …       │ …         │              … │             … │                 … │ … │
        └─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘

        The only valid values of `keep` are `"first"`, `"last"` and [`None][None]

        >>> t.distinct(on="species", keep="second")
        Traceback (most recent call last):
          ...
        ibis.common.exceptions.IbisError: Invalid value for keep: 'second' ...
        """

        import ibis.selectors as s

        if on is None:
            # dedup everything
            if keep != "first":
                raise com.IbisError(
                    f"Only keep='first' (the default) makes sense when deduplicating all columns; got keep={keep!r}"
                )
            return ops.Distinct(self).to_expr()

        if not isinstance(on, s.Selector):
            on = s.c(*util.promote_list(on))

        if keep is None:
            having = lambda t: t.count() == 1
            how = "first"
        elif keep == "first" or keep == "last":
            having = None
            how = keep
        else:
            raise com.IbisError(
                f"Invalid value for `keep`: {keep!r}, must be 'first', 'last' or None"
            )

        aggs = {col.get_name(): col.arbitrary(how=how) for col in (~on).expand(self)}

        gb = self.group_by(on)
        if having is not None:
            gb = gb.having(having)
        res = gb.agg(**aggs)

        assert len(res.columns) == len(self.columns)
        if res.columns != self.columns:
            return res.select(self.columns)
        return res

    def limit(self, n: int, offset: int = 0) -> Table:
        """Select `n` rows from `self` starting at `offset`.

        !!! note "The result set is not deterministic without a call to [`order_by`][ibis.expr.types.relations.Table.order_by]."

        Parameters
        ----------
        n
            Number of rows to include
        offset
            Number of rows to skip first

        Returns
        -------
        Table
            The first `n` rows of `self` starting at `offset`

        Examples
        --------
        >>> import ibis
        >>> ibis.options.interactive = True
        >>> t = ibis.memtable({"a": [1, 1, 2], "b": ["c", "a", "a"]})
        >>> t
        ┏━━━━━━━┳━━━━━━━━┓
        ┃ a     ┃ b      ┃
        ┡━━━━━━━╇━━━━━━━━┩
        │ int64 │ string │
        ├───────┼────────┤
        │     1 │ c      │
        │     1 │ a      │
        │     2 │ a      │
        └───────┴────────┘
        >>> t.limit(2)
        ┏━━━━━━━┳━━━━━━━━┓
        ┃ a     ┃ b      ┃
        ┡━━━━━━━╇━━━━━━━━┩
        │ int64 │ string │
        ├───────┼────────┤
        │     1 │ c      │
        │     1 │ a      │
        └───────┴────────┘

        See Also
        --------
        [`Table.order_by`][ibis.expr.types.relations.Table.order_by]
        """
        return ops.Limit(self, n, offset=offset).to_expr()

    def head(self, n: int = 5) -> Table:
        """Select the first `n` rows of a table.

        !!! note "The result set is not deterministic without a call to [`order_by`][ibis.expr.types.relations.Table.order_by]."

        Parameters
        ----------
        n
            Number of rows to include

        Returns
        -------
        Table
            `self` limited to `n` rows

        Examples
        --------
        >>> import ibis
        >>> ibis.options.interactive = True
        >>> t = ibis.memtable({"a": [1, 1, 2], "b": ["c", "a", "a"]})
        >>> t
        ┏━━━━━━━┳━━━━━━━━┓
        ┃ a     ┃ b      ┃
        ┡━━━━━━━╇━━━━━━━━┩
        │ int64 │ string │
        ├───────┼────────┤
        │     1 │ c      │
        │     1 │ a      │
        │     2 │ a      │
        └───────┴────────┘
        >>> t.head(2)
        ┏━━━━━━━┳━━━━━━━━┓
        ┃ a     ┃ b      ┃
        ┡━━━━━━━╇━━━━━━━━┩
        │ int64 │ string │
        ├───────┼────────┤
        │     1 │ c      │
        │     1 │ a      │
        └───────┴────────┘

        See Also
        --------
        [`Table.limit`][ibis.expr.types.relations.Table.limit]
        [`Table.order_by`][ibis.expr.types.relations.Table.order_by]
        """
        return self.limit(n=n)

    def order_by(
        self,
        by: str
        | ir.Column
        | tuple[str | ir.Column, bool]
        | Sequence[str]
        | Sequence[ir.Column]
        | Sequence[tuple[str | ir.Column, bool]]
        | None,
    ) -> Table:
        """Sort a table by one or more expressions.

        Parameters
        ----------
        by
            Expressions to sort the table by.

        Returns
        -------
        Table
            Sorted table

        Examples
        --------
        >>> import ibis
        >>> ibis.options.interactive = True
        >>> t = ibis.memtable({"a": [1, 2, 3], "b": ["c", "b", "a"], "c": [4, 6, 5]})
        >>> t
        ┏━━━━━━━┳━━━━━━━━┳━━━━━━━┓
        ┃ a     ┃ b      ┃ c     ┃
        ┡━━━━━━━╇━━━━━━━━╇━━━━━━━┩
        │ int64 │ string │ int64 │
        ├───────┼────────┼───────┤
        │     1 │ c      │     4 │
        │     2 │ b      │     6 │
        │     3 │ a      │     5 │
        └───────┴────────┴───────┘
        >>> t.order_by("b")
        ┏━━━━━━━┳━━━━━━━━┳━━━━━━━┓
        ┃ a     ┃ b      ┃ c     ┃
        ┡━━━━━━━╇━━━━━━━━╇━━━━━━━┩
        │ int64 │ string │ int64 │
        ├───────┼────────┼───────┤
        │     3 │ a      │     5 │
        │     2 │ b      │     6 │
        │     1 │ c      │     4 │
        └───────┴────────┴───────┘
        >>> t.order_by(ibis.desc("c"))
        ┏━━━━━━━┳━━━━━━━━┳━━━━━━━┓
        ┃ a     ┃ b      ┃ c     ┃
        ┡━━━━━━━╇━━━━━━━━╇━━━━━━━┩
        │ int64 │ string │ int64 │
        ├───────┼────────┼───────┤
        │     2 │ b      │     6 │
        │     3 │ a      │     5 │
        │     1 │ c      │     4 │
        └───────┴────────┴───────┘
        """
        used_tuple_syntax = False
        if isinstance(by, tuple):
            by = [by]
            used_tuple_syntax = True

        sort_keys = []
        for item in util.promote_list(by):
            if isinstance(item, tuple):
                if len(item) != 2:
                    raise ValueError(
                        "Tuple must be of length 2, got {}".format(len(item))
                    )
                item = (bind_expr(self, item[0]), item[1])
                used_tuple_syntax = True
            else:
                item = bind_expr(self, item)
            sort_keys.append(item)

        if used_tuple_syntax:
            util.warn_deprecated(
                "table.order_by((key, True)) and table.order_by((key, False)) syntax",
                as_of="6.0",
                removed_in="7.0",
                instead="Use ibis.desc(key) or ibis.asc(key) instead",
            )

        return self.op().order_by(sort_keys).to_expr()

    def union(self, table: Table, *rest: Table, distinct: bool = False) -> Table:
        """Compute the set union of multiple table expressions.

        The input tables must have identical schemas.

        Parameters
        ----------
        table
            A table expression
        *rest
            Additional table expressions
        distinct
            Only return distinct rows

        Returns
        -------
        Table
            A new table containing the union of all input tables.

        See Also
        --------
        [`ibis.union`][ibis.union]

        Examples
        --------
        >>> import ibis
        >>> ibis.options.interactive = True
        >>> t1 = ibis.memtable({"a": [1, 2]})
        >>> t1
        ┏━━━━━━━┓
        ┃ a     ┃
        ┡━━━━━━━┩
        │ int64 │
        ├───────┤
        │     1 │
        │     2 │
        └───────┘
        >>> t2 = ibis.memtable({"a": [2, 3]})
        >>> t2
        ┏━━━━━━━┓
        ┃ a     ┃
        ┡━━━━━━━┩
        │ int64 │
        ├───────┤
        │     2 │
        │     3 │
        └───────┘
        >>> t1.union(t2)  # union all by default
        ┏━━━━━━━┓
        ┃ a     ┃
        ┡━━━━━━━┩
        │ int64 │
        ├───────┤
        │     1 │
        │     2 │
        │     2 │
        │     3 │
        └───────┘
        >>> t1.union(t2, distinct=True).order_by("a")
        ┏━━━━━━━┓
        ┃ a     ┃
        ┡━━━━━━━┩
        │ int64 │
        ├───────┤
        │     1 │
        │     2 │
        │     3 │
        └───────┘
        """
        node = ops.Union(self, table, distinct=distinct)
        for table in rest:
            node = ops.Union(node, table, distinct=distinct)
        return node.to_expr().select(self.columns)

    def intersect(self, table: Table, *rest: Table, distinct: bool = True) -> Table:
        """Compute the set intersection of multiple table expressions.

        The input tables must have identical schemas.

        Parameters
        ----------
        table
            A table expression
        *rest
            Additional table expressions
        distinct
            Only return distinct rows

        Returns
        -------
        Table
            A new table containing the intersection of all input tables.

        See Also
        --------
        [`ibis.intersect`][ibis.intersect]

        Examples
        --------
        >>> import ibis
        >>> ibis.options.interactive = True
        >>> t1 = ibis.memtable({"a": [1, 2]})
        >>> t1
        ┏━━━━━━━┓
        ┃ a     ┃
        ┡━━━━━━━┩
        │ int64 │
        ├───────┤
        │     1 │
        │     2 │
        └───────┘
        >>> t2 = ibis.memtable({"a": [2, 3]})
        >>> t2
        ┏━━━━━━━┓
        ┃ a     ┃
        ┡━━━━━━━┩
        │ int64 │
        ├───────┤
        │     2 │
        │     3 │
        └───────┘
        >>> t1.intersect(t2)
        ┏━━━━━━━┓
        ┃ a     ┃
        ┡━━━━━━━┩
        │ int64 │
        ├───────┤
        │     2 │
        └───────┘
        """
        node = ops.Intersection(self, table, distinct=distinct)
        for table in rest:
            node = ops.Intersection(node, table, distinct=distinct)
        return node.to_expr().select(self.columns)

    def to_array(self) -> ir.Column:
        """View a single column table as an array.

        Returns
        -------
        Value
            A single column view of a table
        """
        schema = self.schema()
        if len(schema) != 1:
            raise com.ExpressionError(
                'Table must have exactly one column when viewed as array'
            )

        return ops.TableArrayView(self).to_expr()

    def mutate(
        self, exprs: Sequence[ir.Expr] | None = None, **mutations: ir.Value
    ) -> Table:
        """Add columns to a table expression.

        Parameters
        ----------
        exprs
            List of named expressions to add as columns
        mutations
            Named expressions using keyword arguments

        Returns
        -------
        Table
            Table expression with additional columns

        Examples
        --------
        >>> import ibis
        >>> import ibis.selectors as s
        >>> from ibis import _
        >>> ibis.options.interactive = True
        >>> t = ibis.examples.penguins.fetch().select("species", "year", "bill_length_mm")
        >>> t
        ┏━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━━━━━┓
        ┃ species ┃ year  ┃ bill_length_mm ┃
        ┡━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━━━━━┩
        │ string  │ int64 │ float64        │
        ├─────────┼───────┼────────────────┤
        │ Adelie  │  2007 │           39.1 │
        │ Adelie  │  2007 │           39.5 │
        │ Adelie  │  2007 │           40.3 │
        │ Adelie  │  2007 │            nan │
        │ Adelie  │  2007 │           36.7 │
        │ Adelie  │  2007 │           39.3 │
        │ Adelie  │  2007 │           38.9 │
        │ Adelie  │  2007 │           39.2 │
        │ Adelie  │  2007 │           34.1 │
        │ Adelie  │  2007 │           42.0 │
        │ …       │     … │              … │
        └─────────┴───────┴────────────────┘

        Add a new column from a per-element expression

        >>> t.mutate(next_year=_.year + 1).head()
        ┏━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━┓
        ┃ species ┃ year  ┃ bill_length_mm ┃ next_year ┃
        ┡━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━┩
        │ string  │ int64 │ float64        │ int64     │
        ├─────────┼───────┼────────────────┼───────────┤
        │ Adelie  │  2007 │           39.1 │      2008 │
        │ Adelie  │  2007 │           39.5 │      2008 │
        │ Adelie  │  2007 │           40.3 │      2008 │
        │ Adelie  │  2007 │            nan │      2008 │
        │ Adelie  │  2007 │           36.7 │      2008 │
        └─────────┴───────┴────────────────┴───────────┘

        Add a new column based on an aggregation. Note the automatic broadcasting.

        >>> t.select("species", bill_demean=_.bill_length_mm - _.bill_length_mm.mean()).head()
        ┏━━━━━━━━━┳━━━━━━━━━━━━━┓
        ┃ species ┃ bill_demean ┃
        ┡━━━━━━━━━╇━━━━━━━━━━━━━┩
        │ string  │ float64     │
        ├─────────┼─────────────┤
        │ Adelie  │    -4.82193 │
        │ Adelie  │    -4.42193 │
        │ Adelie  │    -3.62193 │
        │ Adelie  │         nan │
        │ Adelie  │    -7.22193 │
        └─────────┴─────────────┘

        Mutate across multiple columns

        >>> t.mutate(s.across(s.numeric() & ~s.c("year"), _ - _.mean())).head()
        ┏━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━━━━━┓
        ┃ species ┃ year  ┃ bill_length_mm ┃
        ┡━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━━━━━┩
        │ string  │ int64 │ float64        │
        ├─────────┼───────┼────────────────┤
        │ Adelie  │  2007 │       -4.82193 │
        │ Adelie  │  2007 │       -4.42193 │
        │ Adelie  │  2007 │       -3.62193 │
        │ Adelie  │  2007 │            nan │
        │ Adelie  │  2007 │       -7.22193 │
        └─────────┴───────┴────────────────┘
        """
        import ibis.expr.analysis as an

        exprs = [] if exprs is None else util.promote_list(exprs)
        exprs = itertools.chain(
            itertools.chain.from_iterable(
                util.promote_list(_ensure_expr(self, expr)) for expr in exprs
            ),
            (
                e.name(name)
                for name, expr in mutations.items()
                for e in util.promote_list(_ensure_expr(self, expr))
            ),
        )
        mutation_exprs = an.get_mutation_exprs(list(exprs), self)
        return self.select(mutation_exprs)

    def select(
        self,
        *exprs: ir.Value | str | Iterable[ir.Value | str],
        **named_exprs: ir.Value | str,
    ) -> Table:
        """Compute a new table expression using `exprs` and `named_exprs`.

        Passing an aggregate function to this method will broadcast the
        aggregate's value over the number of rows in the table and
        automatically constructs a window function expression. See the examples
        section for more details.

        For backwards compatibility the keyword argument `exprs` is reserved
        and cannot be used to name an expression. This behavior will be removed
        in v4.

        Parameters
        ----------
        exprs
            Column expression, string, or list of column expressions and
            strings.
        named_exprs
            Column expressions

        Returns
        -------
        Table
            Table expression

        Examples
        --------
        >>> import ibis
        >>> 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 │            nan │           nan │              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 │ … │
        │ …       │ …         │              … │             … │                 … │ … │
        └─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘

        Simple projection

        >>> t.select("island", "bill_length_mm").head()
        ┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┓
        ┃ island    ┃ bill_length_mm ┃
        ┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━━┩
        │ string    │ float64        │
        ├───────────┼────────────────┤
        │ Torgersen │           39.1 │
        │ Torgersen │           39.5 │
        │ Torgersen │           40.3 │
        │ Torgersen │            nan │
        │ Torgersen │           36.7 │
        └───────────┴────────────────┘

        Projection by zero-indexed column position

        >>> t.select(0, 4).head()
        ┏━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┓
        ┃ species ┃ flipper_length_mm ┃
        ┡━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━┩
        │ string  │ int64             │
        ├─────────┼───────────────────┤
        │ Adelie  │               181 │
        │ Adelie  │               186 │
        │ Adelie  │               195 │
        │ Adelie  │              NULL │
        │ Adelie  │               193 │
        └─────────┴───────────────────┘

        Projection with renaming and compute in one call

        >>> t.select(next_year=t.year + 1).head()
        ┏━━━━━━━━━━━┓
        ┃ next_year ┃
        ┡━━━━━━━━━━━┩
        │ int64     │
        ├───────────┤
        │      2008 │
        │      2008 │
        │      2008 │
        │      2008 │
        │      2008 │
        └───────────┘

        Projection with aggregation expressions

        >>> t.select("island", bill_mean=t.bill_length_mm.mean()).head()
        ┏━━━━━━━━━━━┳━━━━━━━━━━━┓
        ┃ island    ┃ bill_mean ┃
        ┡━━━━━━━━━━━╇━━━━━━━━━━━┩
        │ string    │ float64   │
        ├───────────┼───────────┤
        │ Torgersen │  43.92193 │
        │ Torgersen │  43.92193 │
        │ Torgersen │  43.92193 │
        │ Torgersen │  43.92193 │
        │ Torgersen │  43.92193 │
        └───────────┴───────────┘

        Projection with a selector

        >>> import ibis.selectors as s
        >>> t.select(s.numeric() & ~s.c("year")).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 │
        │            nan │           nan │              NULL │        NULL │
        │           36.7 │          19.3 │               193 │        3450 │
        └────────────────┴───────────────┴───────────────────┴─────────────┘

        Projection + aggregation across multiple columns

        >>> from ibis import _
        >>> t.select(s.across(s.numeric() & ~s.c("year"), _.mean())).head()
        ┏━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┓
        ┃ bill_length_mm ┃ bill_depth_mm ┃ flipper_length_mm ┃ body_mass_g ┃
        ┡━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━┩
        │ float64        │ float64       │ float64           │ float64     │
        ├────────────────┼───────────────┼───────────────────┼─────────────┤
        │       43.92193 │      17.15117 │        200.915205 │ 4201.754386 │
        │       43.92193 │      17.15117 │        200.915205 │ 4201.754386 │
        │       43.92193 │      17.15117 │        200.915205 │ 4201.754386 │
        │       43.92193 │      17.15117 │        200.915205 │ 4201.754386 │
        │       43.92193 │      17.15117 │        200.915205 │ 4201.754386 │
        └────────────────┴───────────────┴───────────────────┴─────────────┘
        """
        import ibis.expr.analysis as an
        from ibis.selectors import Selector

        exprs = list(
            itertools.chain(
                itertools.chain.from_iterable(
                    util.promote_list(e.expand(self) if isinstance(e, Selector) else e)
                    for e in exprs
                ),
                (
                    self._ensure_expr(expr).name(name)
                    for name, expr in named_exprs.items()
                ),
            )
        )

        if not exprs:
            raise com.IbisTypeError(
                "You must select at least one column for a valid projection"
            )

        op = an.Projector(self, exprs).get_result()

        return op.to_expr()

    projection = select

    def relabel(
        self,
        substitutions: Mapping[str, str]
        | Callable[[str], str | None]
        | str
        | Literal["snake_case", "ALL_CAPS"],
    ) -> Table:
        """Rename columns in the table.

        Parameters
        ----------
        substitutions
            A mapping, function, or format string mapping old to new column
            names. If a column isn't in the mapping (or if the callable returns
            None) it is left with its original name. May also pass a format
            string to rename all columns, like ``"prefix_{name}"``. Also
            accepts the literal string ``"snake_case"`` or ``"ALL_CAPS"`` which
            will relabel all columns to use a ``snake_case`` or ``"ALL_CAPS"``
            naming convention.

        Returns
        -------
        Table
            A relabeled table expression

        Examples
        --------
        >>> import ibis
        >>> import ibis.selectors as s
        >>> ibis.options.interactive = True
        >>> first3 = s.r[:3]  # first 3 columns
        >>> t = ibis.examples.penguins_raw_raw.fetch().select(first3)
        >>> t
        ┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
        ┃ studyName ┃ Sample Number ┃ Species                             ┃
        ┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
        │ string    │ int64         │ string                              │
        ├───────────┼───────────────┼─────────────────────────────────────┤
        │ PAL0708   │             1 │ Adelie Penguin (Pygoscelis adeliae) │
        │ PAL0708   │             2 │ Adelie Penguin (Pygoscelis adeliae) │
        │ PAL0708   │             3 │ Adelie Penguin (Pygoscelis adeliae) │
        │ PAL0708   │             4 │ Adelie Penguin (Pygoscelis adeliae) │
        │ PAL0708   │             5 │ Adelie Penguin (Pygoscelis adeliae) │
        │ PAL0708   │             6 │ Adelie Penguin (Pygoscelis adeliae) │
        │ PAL0708   │             7 │ Adelie Penguin (Pygoscelis adeliae) │
        │ PAL0708   │             8 │ Adelie Penguin (Pygoscelis adeliae) │
        │ PAL0708   │             9 │ Adelie Penguin (Pygoscelis adeliae) │
        │ PAL0708   │            10 │ Adelie Penguin (Pygoscelis adeliae) │
        │ …         │             … │ …                                   │
        └───────────┴───────────────┴─────────────────────────────────────┘

        Relabel column names using a mapping from old name to new name

        >>> t.relabel({"studyName": "study_name"}).head(1)
        ┏━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
        ┃ study_name ┃ Sample Number ┃ Species                             ┃
        ┡━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
        │ string     │ int64         │ string                              │
        ├────────────┼───────────────┼─────────────────────────────────────┤
        │ PAL0708    │             1 │ Adelie Penguin (Pygoscelis adeliae) │
        └────────────┴───────────────┴─────────────────────────────────────┘

        Relabel column names using a snake_case convention

        >>> t.relabel("snake_case").head(1)
        ┏━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
        ┃ study_name ┃ sample_number ┃ species                             ┃
        ┡━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
        │ string     │ int64         │ string                              │
        ├────────────┼───────────────┼─────────────────────────────────────┤
        │ PAL0708    │             1 │ Adelie Penguin (Pygoscelis adeliae) │
        └────────────┴───────────────┴─────────────────────────────────────┘

        Relabel column names using a ALL_CAPS convention

        >>> t.relabel("ALL_CAPS").head(1)
        ┏━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
        ┃ STUDY_NAME ┃ SAMPLE_NUMBER ┃ SPECIES                             ┃
        ┡━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
        │ string     │ int64         │ string                              │
        ├────────────┼───────────────┼─────────────────────────────────────┤
        │ PAL0708    │             1 │ Adelie Penguin (Pygoscelis adeliae) │
        └────────────┴───────────────┴─────────────────────────────────────┘

        Relabel columns using a format string

        >>> t.relabel("p_{name}").head(1)
        ┏━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
        ┃ p_studyName ┃ p_Sample Number ┃ p_Species                           ┃
        ┡━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
        │ string      │ int64           │ string                              │
        ├─────────────┼─────────────────┼─────────────────────────────────────┤
        │ PAL0708     │               1 │ Adelie Penguin (Pygoscelis adeliae) │
        └─────────────┴─────────────────┴─────────────────────────────────────┘

        Relabel column names using a callable

        >>> t.relabel(str.upper).head(1)
        ┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
        ┃ STUDYNAME ┃ SAMPLE NUMBER ┃ SPECIES                             ┃
        ┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
        │ string    │ int64         │ string                              │
        ├───────────┼───────────────┼─────────────────────────────────────┤
        │ PAL0708   │             1 │ Adelie Penguin (Pygoscelis adeliae) │
        └───────────┴───────────────┴─────────────────────────────────────┘
        """
        observed = set()

        if isinstance(substitutions, Mapping):
            rename = substitutions.get
        elif substitutions in {"snake_case", "ALL_CAPS"}:

            def rename(c):
                c = c.strip()
                if " " in c:
                    # Handle "space case possibly with-hyphens"
                    if substitutions == "snake_case":
                        return "_".join(c.lower().split()).replace("-", "_")
                    elif substitutions == "ALL_CAPS":
                        return "_".join(c.upper().split()).replace("-", "_")
                # Handle PascalCase, camelCase, and kebab-case
                c = re.sub(r"([A-Z]+)([A-Z][a-z])", r'\1_\2', c)
                c = re.sub(r"([a-z\d])([A-Z])", r'\1_\2', c)
                c = c.replace("-", "_")
                if substitutions == "snake_case":
                    return c.lower()
                elif substitutions == "ALL_CAPS":
                    return c.upper()

        elif isinstance(substitutions, str):

            def rename(name):
                return substitutions.format(name=name)

            # Detect the case of missing or extra format string parameters
            try:
                dummy_name1 = "_unlikely_column_name_1_"
                dummy_name2 = "_unlikely_column_name_2_"
                invalid = rename(dummy_name1) == rename(dummy_name2)
            except KeyError:
                invalid = True
            if invalid:
                raise ValueError("Format strings must take a single parameter `name`")
        else:
            rename = substitutions

        exprs = []
        for c in self.columns:
            expr = self[c]
            if (name := rename(c)) is not None:
                expr = expr.name(name)
                observed.add(c)
            exprs.append(expr)

        if isinstance(substitutions, Mapping):
            for c in substitutions:
                if c not in observed:
                    raise KeyError(f"{c!r} is not an existing column")

        return self.select(exprs)

    def drop(self, *fields: str | Selector) -> Table:
        """Remove fields from a table.

        Parameters
        ----------
        fields
            Fields to drop. Strings and selectors are accepted.

        Returns
        -------
        Table
            A table with all columns matching `fields` removed.

        Examples
        --------
        >>> import ibis
        >>> 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 │            nan │           nan │              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 │ … │
        │ …       │ …         │              … │             … │                 … │ … │
        └─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘

        Drop one or more columns

        >>> t.drop("species").head()
        ┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
        ┃ island    ┃ bill_length_mm ┃ bill_depth_mm ┃ flipper_length_mm ┃ … ┃
        ┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━┩
        │ string    │ float64        │ float64       │ int64             │ … │
        ├───────────┼────────────────┼───────────────┼───────────────────┼───┤
        │ Torgersen │           39.1 │          18.7 │               181 │ … │
        │ Torgersen │           39.5 │          17.4 │               186 │ … │
        │ Torgersen │           40.3 │          18.0 │               195 │ … │
        │ Torgersen │            nan │           nan │              NULL │ … │
        │ Torgersen │           36.7 │          19.3 │               193 │ … │
        └───────────┴────────────────┴───────────────┴───────────────────┴───┘
        >>> t.drop("species", "bill_length_mm").head()
        ┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━┓
        ┃ island    ┃ bill_depth_mm ┃ flipper_length_mm ┃ body_mass_g ┃ sex    ┃ … ┃
        ┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━┩
        │ string    │ float64       │ int64             │ int64       │ string │ … │
        ├───────────┼───────────────┼───────────────────┼─────────────┼────────┼───┤
        │ Torgersen │          18.7 │               181 │        3750 │ male   │ … │
        │ Torgersen │          17.4 │               186 │        3800 │ female │ … │
        │ Torgersen │          18.0 │               195 │        3250 │ female │ … │
        │ Torgersen │           nan │              NULL │        NULL │ NULL   │ … │
        │ Torgersen │          19.3 │               193 │        3450 │ female │ … │
        └───────────┴───────────────┴───────────────────┴─────────────┴────────┴───┘

        Drop with selectors, mix and match

        >>> import ibis.selectors as s
        >>> t.drop("species", s.startswith("bill_")).head()
        ┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━┓
        ┃ island    ┃ flipper_length_mm ┃ body_mass_g ┃ sex    ┃ year  ┃
        ┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━┩
        │ string    │ int64             │ int64       │ string │ int64 │
        ├───────────┼───────────────────┼─────────────┼────────┼───────┤
        │ Torgersen │               181 │        3750 │ male   │  2007 │
        │ Torgersen │               186 │        3800 │ female │  2007 │
        │ Torgersen │               195 │        3250 │ female │  2007 │
        │ Torgersen │              NULL │        NULL │ NULL   │  2007 │
        │ Torgersen │               193 │        3450 │ female │  2007 │
        └───────────┴───────────────────┴─────────────┴────────┴───────┘
        """
        from ibis import selectors as s

        if not fields:
            # no-op if nothing to be dropped
            return self

        if missing_fields := {f for f in fields if isinstance(f, str)}.difference(
            self.schema().names
        ):
            raise KeyError(f"Fields not in table: {sorted(missing_fields)}")

        sels = (s.c(f) if isinstance(f, str) else f for f in fields)
        return self.select(~s.any_of(*sels))

    def filter(
        self,
        predicates: ir.BooleanValue | Sequence[ir.BooleanValue] | IfAnyAll,
    ) -> Table:
        """Select rows from `table` based on `predicates`.

        Parameters
        ----------
        predicates
            Boolean value expressions used to select rows in `table`.

        Returns
        -------
        Table
            Filtered table expression

        Examples
        --------
        >>> import ibis
        >>> 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 │            nan │           nan │              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 │ … │
        │ …       │ …         │              … │             … │                 … │ … │
        └─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
        >>> t.filter([t.species == "Adelie", t.body_mass_g > 3500]).sex.value_counts().dropna("sex")
        ┏━━━━━━━━┳━━━━━━━━━━━┓
        ┃ sex    ┃ sex_count ┃
        ┡━━━━━━━━╇━━━━━━━━━━━┩
        │ string │ int64     │
        ├────────┼───────────┤
        │ male   │        68 │
        │ female │        22 │
        └────────┴───────────┘
        """
        import ibis.expr.analysis as an

        resolved_predicates = _resolve_predicates(self, predicates)
        predicates = [
            an._rewrite_filter(pred.op() if isinstance(pred, Expr) else pred)
            for pred in resolved_predicates
        ]
        return an.apply_filter(self.op(), predicates).to_expr()

    def nunique(self, where: ir.BooleanValue | None = None) -> ir.IntegerScalar:
        """Compute the number of unique rows in the table.

        Parameters
        ----------
        where
            Optional boolean expression to filter rows when counting.

        Returns
        -------
        IntegerScalar
            Number of unique rows in the table

        Examples
        --------
        >>> import ibis
        >>> ibis.options.interactive = True
        >>> t = ibis.memtable({"a": ["foo", "bar", "bar"]})
        >>> t
        ┏━━━━━━━━┓
        ┃ a      ┃
        ┡━━━━━━━━┩
        │ string │
        ├────────┤
        │ foo    │
        │ bar    │
        │ bar    │
        └────────┘
        >>> t.nunique()
        2
        >>> t.nunique(t.a != "foo")
        1
        """
        return ops.CountDistinctStar(self, where=where).to_expr()

    def count(self, where: ir.BooleanValue | None = None) -> ir.IntegerScalar:
        """Compute the number of rows in the table.

        Parameters
        ----------
        where
            Optional boolean expression to filter rows when counting.

        Returns
        -------
        IntegerScalar
            Number of rows in the table

        Examples
        --------
        >>> import ibis
        >>> ibis.options.interactive = True
        >>> t = ibis.memtable({"a": ["foo", "bar", "baz"]})
        >>> t
        ┏━━━━━━━━┓
        ┃ a      ┃
        ┡━━━━━━━━┩
        │ string │
        ├────────┤
        │ foo    │
        │ bar    │
        │ baz    │
        └────────┘
        >>> t.count()
        3
        >>> t.count(t.a != "foo")
        2
        >>> type(t.count())
        <class 'ibis.expr.types.numeric.IntegerScalar'>
        """
        return ops.CountStar(self, where).to_expr()

    def dropna(
        self,
        subset: Sequence[str] | str | None = None,
        how: Literal["any", "all"] = "any",
    ) -> Table:
        """Remove rows with null values from the table.

        Parameters
        ----------
        subset
            Columns names to consider when dropping nulls. By default all columns
            are considered.
        how
            Determine whether a row is removed if there is **at least one null
            value in the row** (`'any'`), or if **all** row values are null
            (`'all'`).

        Returns
        -------
        Table
            Table expression

        Examples
        --------
        >>> import ibis
        >>> 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 │            nan │           nan │              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 │ … │
        │ …       │ …         │              … │             … │                 … │ … │
        └─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
        >>> t.count()
        344
        >>> t.dropna(["bill_length_mm", "body_mass_g"]).count()
        342
        >>> t.dropna(how="all").count()  # no rows where all columns are null
        344
        """
        if subset is not None:
            subset = bind_expr(self, util.promote_list(subset))
        return ops.DropNa(self, how, subset).to_expr()

    def fillna(
        self,
        replacements: ir.Scalar | Mapping[str, ir.Scalar],
    ) -> Table:
        """Fill null values in a table expression.

        !!! note "There is potential lack of type stability with the `fillna` API"

            For example, different library versions may impact whether a given
            backend promotes integer replacement values to floats.

        Parameters
        ----------
        replacements
            Value with which to fill nulls. If `replacements` is a mapping, the
            keys are column names that map to their replacement value. If
            passed as a scalar all columns are filled with that value.

        Examples
        --------
        >>> import ibis
        >>> ibis.options.interactive = True
        >>> t = ibis.examples.penguins.fetch()
        >>> t.sex
        ┏━━━━━━━━┓
        ┃ sex    ┃
        ┡━━━━━━━━┩
        │ string │
        ├────────┤
        │ male   │
        │ female │
        │ female │
        │ NULL   │
        │ female │
        │ male   │
        │ female │
        │ male   │
        │ NULL   │
        │ NULL   │
        │ …      │
        └────────┘
        >>> t.fillna({"sex": "unrecorded"}).sex
        ┏━━━━━━━━━━━━┓
        ┃ sex        ┃
        ┡━━━━━━━━━━━━┩
        │ string     │
        ├────────────┤
        │ male       │
        │ female     │
        │ female     │
        │ unrecorded │
        │ female     │
        │ male       │
        │ female     │
        │ male       │
        │ unrecorded │
        │ unrecorded │
        │ …          │
        └────────────┘

        Returns
        -------
        Table
            Table expression
        """
        schema = self.schema()

        if isinstance(replacements, collections.abc.Mapping):
            for col, val in replacements.items():
                if col not in schema:
                    columns_formatted = ', '.join(map(repr, schema.names))
                    raise com.IbisTypeError(
                        f"Column {col!r} is not found in table. "
                        f"Existing columns: {columns_formatted}."
                    ) from None

                col_type = schema[col]
                val_type = val.type() if isinstance(val, Expr) else dt.infer(val)
                if not dt.castable(val_type, col_type):
                    raise com.IbisTypeError(
                        f"Cannot fillna on column {col!r} of type {col_type} with a "
                        f"value of type {val_type}"
                    )
        else:
            val_type = (
                replacements.type()
                if isinstance(replacements, Expr)
                else dt.infer(replacements)
            )
            for col, col_type in schema.items():
                if col_type.nullable and not dt.castable(val_type, col_type):
                    raise com.IbisTypeError(
                        f"Cannot fillna on column {col!r} of type {col_type} with a "
                        f"value of type {val_type} - pass in an explicit mapping "
                        f"of fill values to `fillna` instead."
                    )
        return ops.FillNa(self, replacements).to_expr()

    def unpack(self, *columns: str) -> Table:
        """Project the struct fields of each of `columns` into `self`.

        Existing fields are retained in the projection.

        Parameters
        ----------
        columns
            String column names to project into `self`.

        Returns
        -------
        Table
            The child table with struct fields of each of `columns` projected.

        Examples
        --------
        >>> import ibis
        >>> ibis.options.interactive = True
        >>> lines = '''
        ...     {"name": "a", "pos": {"lat": 10.1, "lon": 30.3}}
        ...     {"name": "b", "pos": {"lat": 10.2, "lon": 30.2}}
        ...     {"name": "c", "pos": {"lat": 10.3, "lon": 30.1}}
        ... '''
        >>> with open("/tmp/lines.json", "w") as f:
        ...     _ = f.write(lines)
        >>> t = ibis.read_json("/tmp/lines.json")
        >>> t
        ┏━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
        ┃ name   ┃ pos                                ┃
        ┡━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
        │ string │ struct<lat: float64, lon: float64> │
        ├────────┼────────────────────────────────────┤
        │ a      │ {'lat': 10.1, 'lon': 30.3}         │
        │ b      │ {'lat': 10.2, 'lon': 30.2}         │
        │ c      │ {'lat': 10.3, 'lon': 30.1}         │
        └────────┴────────────────────────────────────┘
        >>> t.unpack("pos")
        ┏━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┓
        ┃ name   ┃ lat     ┃ lon     ┃
        ┡━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━┩
        │ string │ float64 │ float64 │
        ├────────┼─────────┼─────────┤
        │ a      │    10.1 │    30.3 │
        │ b      │    10.2 │    30.2 │
        │ c      │    10.3 │    30.1 │
        └────────┴─────────┴─────────┘

        See Also
        --------
        [`StructValue.lift`][ibis.expr.types.structs.StructValue.lift]
        """
        columns_to_unpack = frozenset(columns)
        result_columns = []
        for column in self.columns:
            if column in columns_to_unpack:
                expr = self[column]
                result_columns.extend(expr[field] for field in expr.names)
            else:
                result_columns.append(column)
        return self[result_columns]

    def info(self) -> Table:
        """Return summary information about a table.

        Returns
        -------
        Table
            Summary of `self`

        Examples
        --------
        >>> import ibis
        >>> ibis.options.interactive = True
        >>> t = ibis.examples.penguins.fetch()
        >>> t.info()
        ┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━┳━━━┓
        ┃ name              ┃ type    ┃ nullable ┃ nulls ┃ non_nulls ┃ null_frac ┃ … ┃
        ┡━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━╇━━━┩
        │ string            │ string  │ boolean  │ int64 │ int64     │ float64   │ … │
        ├───────────────────┼─────────┼──────────┼───────┼───────────┼───────────┼───┤
        │ species           │ string  │ True     │     0 │       344 │  0.000000 │ … │
        │ island            │ string  │ True     │     0 │       344 │  0.000000 │ … │
        │ bill_length_mm    │ float64 │ True     │     2 │       342 │  0.005814 │ … │
        │ bill_depth_mm     │ float64 │ True     │     2 │       342 │  0.005814 │ … │
        │ flipper_length_mm │ int64   │ True     │     2 │       342 │  0.005814 │ … │
        │ body_mass_g       │ int64   │ True     │     2 │       342 │  0.005814 │ … │
        │ sex               │ string  │ True     │    11 │       333 │  0.031977 │ … │
        │ year              │ int64   │ True     │     0 │       344 │  0.000000 │ … │
        └───────────────────┴─────────┴──────────┴───────┴───────────┴───────────┴───┘
        """
        from ibis import literal as lit

        aggs = []

        for pos, colname in enumerate(self.columns):
            col = self[colname]
            typ = col.type()
            agg = self.select(
                isna=ibis.case().when(col.isnull(), 1).else_(0).end()
            ).agg(
                name=lit(colname),
                type=lit(str(typ)),
                nullable=lit(int(typ.nullable)).cast("bool"),
                nulls=lambda t: t.isna.sum(),
                non_nulls=lambda t: (1 - t.isna).sum(),
                null_frac=lambda t: t.isna.mean(),
                pos=lit(pos),
            )
            aggs.append(agg)
        return ibis.union(*aggs).order_by(ibis.asc("pos"))

    def join(
        left: Table,
        right: Table,
        predicates: str
        | Sequence[
            str | tuple[str | ir.Column, str | ir.Column] | ir.BooleanColumn
        ] = (),
        how: Literal[
            'inner',
            'left',
            'outer',
            'right',
            'semi',
            'anti',
            'any_inner',
            'any_left',
            'left_semi',
        ] = 'inner',
        *,
        lname: str = "",
        rname: str = "{name}_right",
    ) -> Table:
        """Perform a join between two tables.

        Parameters
        ----------
        left
            Left table to join
        right
            Right table to join
        predicates
            Boolean or column names to join on
        how
            Join method
        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}"``).

        Examples
        --------
        >>> import ibis
        >>> import ibis.selectors as s
        >>> import ibis.examples as ex
        >>> from ibis import _
        >>> ibis.options.interactive = True
        >>> movies = ex.ml_latest_small_movies.fetch()
        >>> movies
        ┏━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
        ┃ movieId ┃ title                            ┃ genres                          ┃
        ┡━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
        │ int64   │ string                           │ string                          │
        ├─────────┼──────────────────────────────────┼─────────────────────────────────┤
        │       1 │ Toy Story (1995)                 │ Adventure|Animation|Children|C… │
        │       2 │ Jumanji (1995)                   │ Adventure|Children|Fantasy      │
        │       3 │ Grumpier Old Men (1995)          │ Comedy|Romance                  │
        │       4 │ Waiting to Exhale (1995)         │ Comedy|Drama|Romance            │
        │       5 │ Father of the Bride Part II (19… │ Comedy                          │
        │       6 │ Heat (1995)                      │ Action|Crime|Thriller           │
        │       7 │ Sabrina (1995)                   │ Comedy|Romance                  │
        │       8 │ Tom and Huck (1995)              │ Adventure|Children              │
        │       9 │ Sudden Death (1995)              │ Action                          │
        │      10 │ GoldenEye (1995)                 │ Action|Adventure|Thriller       │
        │       … │ …                                │ …                               │
        └─────────┴──────────────────────────────────┴─────────────────────────────────┘
        >>> links = ex.ml_latest_small_links.fetch()
        >>> links
        ┏━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┓
        ┃ movieId ┃ imdbId  ┃ tmdbId ┃
        ┡━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━┩
        │ int64   │ string  │ int64  │
        ├─────────┼─────────┼────────┤
        │       1 │ 0114709 │    862 │
        │       2 │ 0113497 │   8844 │
        │       3 │ 0113228 │  15602 │
        │       4 │ 0114885 │  31357 │
        │       5 │ 0113041 │  11862 │
        │       6 │ 0113277 │    949 │
        │       7 │ 0114319 │  11860 │
        │       8 │ 0112302 │  45325 │
        │       9 │ 0114576 │   9091 │
        │      10 │ 0113189 │    710 │
        │       … │ …       │      … │
        └─────────┴─────────┴────────┘

        Implicit inner equality join on the shared `movieId` column

        >>> linked = movies.join(links, "movieId", how="inner")
        >>> linked.head()
        ┏━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┓
        ┃ movieId ┃ title                  ┃ genres                 ┃ imdbId  ┃ tmdbId ┃
        ┡━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━┩
        │ int64   │ string                 │ string                 │ string  │ int64  │
        ├─────────┼────────────────────────┼────────────────────────┼─────────┼────────┤
        │       1 │ Toy Story (1995)       │ Adventure|Animation|C… │ 0114709 │    862 │
        │       2 │ Jumanji (1995)         │ Adventure|Children|Fa… │ 0113497 │   8844 │
        │       3 │ Grumpier Old Men (199… │ Comedy|Romance         │ 0113228 │  15602 │
        │       4 │ Waiting to Exhale (19… │ Comedy|Drama|Romance   │ 0114885 │  31357 │
        │       5 │ Father of the Bride P… │ Comedy                 │ 0113041 │  11862 │
        └─────────┴────────────────────────┴────────────────────────┴─────────┴────────┘

        Explicit equality join using the default `how` value of `"inner"`

        >>> linked = movies.join(links, movies.movieId == links.movieId)
        >>> linked.head()
        ┏━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┓
        ┃ movieId ┃ title                  ┃ genres                 ┃ imdbId  ┃ tmdbId ┃
        ┡━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━┩
        │ int64   │ string                 │ string                 │ string  │ int64  │
        ├─────────┼────────────────────────┼────────────────────────┼─────────┼────────┤
        │       1 │ Toy Story (1995)       │ Adventure|Animation|C… │ 0114709 │    862 │
        │       2 │ Jumanji (1995)         │ Adventure|Children|Fa… │ 0113497 │   8844 │
        │       3 │ Grumpier Old Men (199… │ Comedy|Romance         │ 0113228 │  15602 │
        │       4 │ Waiting to Exhale (19… │ Comedy|Drama|Romance   │ 0114885 │  31357 │
        │       5 │ Father of the Bride P… │ Comedy                 │ 0113041 │  11862 │
        └─────────┴────────────────────────┴────────────────────────┴─────────┴────────┘
        """

        _join_classes = {
            'inner': ops.InnerJoin,
            'left': ops.LeftJoin,
            'any_inner': ops.AnyInnerJoin,
            'any_left': ops.AnyLeftJoin,
            'outer': ops.OuterJoin,
            'right': ops.RightJoin,
            'left_semi': ops.LeftSemiJoin,
            'semi': ops.LeftSemiJoin,
            'anti': ops.LeftAntiJoin,
            'cross': ops.CrossJoin,
        }

        klass = _join_classes[how.lower()]
        expr = klass(left, right, predicates).to_expr()

        # semi/anti join only give access to the left table's fields, so
        # there's never overlap
        if how in ("left_semi", "semi", "anti"):
            return expr

        return ops.relations._dedup_join_columns(expr, lname=lname, rname=rname)

    def asof_join(
        left: Table,
        right: Table,
        predicates: str | ir.BooleanColumn | Sequence[str | ir.BooleanColumn] = (),
        by: str | ir.Column | Sequence[str | ir.Column] = (),
        tolerance: str | ir.IntervalScalar | None = None,
        *,
        lname: str = "",
        rname: str = "{name}_right",
    ) -> Table:
        """Perform an "as-of" join between `left` and `right`.

        Similar to a left join except that the match is done on nearest key
        rather than equal keys.

        Optionally, match keys with `by` before joining with `predicates`.

        Parameters
        ----------
        left
            Table expression
        right
            Table expression
        predicates
            Join expressions
        by
            column to group by before joining
        tolerance
            Amount of time to look behind when joining
        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
            Table expression
        """
        op = ops.AsOfJoin(
            left=left,
            right=right,
            predicates=predicates,
            by=by,
            tolerance=tolerance,
        )
        return ops.relations._dedup_join_columns(op.to_expr(), lname=lname, rname=rname)

    def cross_join(
        left: Table,
        right: Table,
        *rest: Table,
        lname: str = "",
        rname: str = "{name}_right",
    ) -> Table:
        """Compute the cross join of a sequence of tables.

        Parameters
        ----------
        left
            Left table
        right
            Right table
        rest
            Additional tables to cross join
        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
            Cross join of `left`, `right` and `rest`

        Examples
        --------
        >>> import ibis
        >>> import ibis.selectors as s
        >>> from ibis import _
        >>> ibis.options.interactive = True
        >>> t = ibis.examples.penguins.fetch()
        >>> t.count()
        344
        >>> agg = t.drop("year").agg(s.across(s.numeric(), _.mean()))
        >>> expr = t.cross_join(agg)
        >>> expr
        ┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
        ┃ 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 │            nan │           nan │              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 │ … │
        │ …       │ …         │              … │             … │                 … │ … │
        └─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
        >>> expr.columns
        ['species',
         'island',
         'bill_length_mm',
         'bill_depth_mm',
         'flipper_length_mm',
         'body_mass_g',
         'sex',
         'year',
         'bill_length_mm_right',
         'bill_depth_mm_right',
         'flipper_length_mm_right',
         'body_mass_g_right']
        >>> expr.count()
        344
        """
        op = ops.CrossJoin(
            left,
            functools.reduce(Table.cross_join, rest, right),
            [],
        )
        return ops.relations._dedup_join_columns(op.to_expr(), lname=lname, rname=rname)

    inner_join = _regular_join_method("inner_join", "inner")
    left_join = _regular_join_method("left_join", "left")
    outer_join = _regular_join_method("outer_join", "outer")
    right_join = _regular_join_method("right_join", "right")
    semi_join = _regular_join_method("semi_join", "semi")
    anti_join = _regular_join_method("anti_join", "anti")
    any_inner_join = _regular_join_method("any_inner_join", "any_inner")
    any_left_join = _regular_join_method("any_left_join", "any_left")

    def alias(self, alias: str) -> ir.Table:
        """Create a table expression with a specific name `alias`.

        This method is useful for exposing an ibis expression to the underlying
        backend for use in the
        [`Table.sql`][ibis.expr.types.relations.Table.sql] method.

        !!! note "`.alias` will create a temporary view"

            `.alias` creates a temporary view in the database.

            This side effect will be removed in a future version of ibis and
            **is not part of the public API**.

        Parameters
        ----------
        alias
            Name of the child expression

        Returns
        -------
        Table
            An table expression

        Examples
        --------
        >>> import ibis
        >>> ibis.options.interactive = True
        >>> t = ibis.examples.penguins.fetch()
        >>> expr = t.alias("pingüinos").sql('SELECT * FROM "pingüinos" LIMIT 5')
        >>> expr
        ┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
        ┃ 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 │            nan │           nan │              NULL │ … │
        │ Adelie  │ Torgersen │           36.7 │          19.3 │               193 │ … │
        └─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
        """
        expr = ops.View(child=self, name=alias).to_expr()

        # NB: calling compile is necessary so that any temporary views are
        # created so that we can infer the schema without executing the entire
        # query
        expr.compile()
        return expr

    def sql(self, query: str, dialect: str | None = None) -> ir.Table:
        '''Run a SQL query against a table expression.

        Parameters
        ----------
        query
            Query string
        dialect
            Optional string indicating the dialect of `query`. Defaults to the
            backend's native dialect.

        Returns
        -------
        Table
            An opaque table expression

        Examples
        --------
        >>> import ibis
        >>> from ibis import _
        >>> ibis.options.interactive = True
        >>> t = ibis.examples.penguins.fetch(table_name="penguins")
        >>> expr = t.sql(
        ...     """
        ...     SELECT island, mean(bill_length_mm) AS avg_bill_length
        ...     FROM penguins
        ...     GROUP BY 1
        ...     ORDER BY 2 DESC
        ...     """
        ... )
        >>> expr
        ┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┓
        ┃ island    ┃ avg_bill_length ┃
        ┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━┩
        │ string    │ float64         │
        ├───────────┼─────────────────┤
        │ Biscoe    │       45.257485 │
        │ Dream     │       44.167742 │
        │ Torgersen │       38.950980 │
        └───────────┴─────────────────┘

        Mix and match ibis expressions with SQL queries

        >>> t = ibis.examples.penguins.fetch(table_name="penguins")
        >>> expr = t.sql(
        ...     """
        ...     SELECT island, mean(bill_length_mm) AS avg_bill_length
        ...     FROM penguins
        ...     GROUP BY 1
        ...     ORDER BY 2 DESC
        ...     """
        ... )
        >>> expr = expr.mutate(
        ...     island=_.island.lower(),
        ...     avg_bill_length=_.avg_bill_length.round(1),
        ... )
        >>> expr
        ┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┓
        ┃ island    ┃ avg_bill_length ┃
        ┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━┩
        │ string    │ float64         │
        ├───────────┼─────────────────┤
        │ biscoe    │            45.3 │
        │ dream     │            44.2 │
        │ torgersen │            39.0 │
        └───────────┴─────────────────┘

        Because ibis expressions aren't named, they aren't visible to
        subsequent `.sql` calls. Use the [`alias`][ibis.expr.types.relations.Table.alias] method
        to assign a name to an expression.

        >>> expr.alias("b").sql("SELECT * FROM b WHERE avg_bill_length > 40")
        ┏━━━━━━━━┳━━━━━━━━━━━━━━━━━┓
        ┃ island ┃ avg_bill_length ┃
        ┡━━━━━━━━╇━━━━━━━━━━━━━━━━━┩
        │ string │ float64         │
        ├────────┼─────────────────┤
        │ biscoe │            45.3 │
        │ dream  │            44.2 │
        └────────┴─────────────────┘

        See Also
        --------
        [`Table.alias`][ibis.expr.types.relations.Table.alias]
        '''

        # only transpile if dialect was passed
        if dialect is not None:
            backend = self._find_backend()
            query = backend._transpile_sql(query, dialect=dialect)
        op = ops.SQLStringView(child=self, name=next(_ALIASES), query=query)
        return op.to_expr()

    def to_pandas(self, **kwargs) -> pd.DataFrame:
        """Convert a table expression to a pandas DataFrame.

        Parameters
        ----------
        kwargs
            Same as keyword arguments to [`execute`][ibis.expr.types.core.Expr.execute]
        """
        return self.execute(**kwargs)

    def cache(self) -> Table:
        """Cache the provided expression.

        All subsequent operations on the returned expression will be performed
        on the cached data. Use the
        [`with`](https://docs.python.org/3/reference/compound_stmts.html#with)
        statement to limit the lifetime of a cached table.

        This method is idempotent: calling it multiple times in succession will
        return the same value as the first call.

        !!! note "This method eagerly evaluates the expression prior to caching"

            Subsequent evaluations will not recompute the expression so method
            chaining will not incur the overhead of caching more than once.

        Returns
        -------
        Table
            Cached table

        Examples
        --------
        >>> import ibis
        >>> ibis.options.interactive = True
        >>> t = ibis.examples.penguins.fetch()
        >>> cached_penguins = t.mutate(computation="Heavy Computation").cache()
        >>> cached_penguins
        ┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
        ┃ 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 │            nan │           nan │              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 │ … │
        │ …       │ …         │              … │             … │                 … │ … │
        └─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘

        Explicit cache cleanup

        >>> with t.mutate(computation="Heavy Computation").cache() as cached_penguins:
        ...     cached_penguins
        ┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
        ┃ 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 │            nan │           nan │              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 │ … │
        │ …       │ …         │              … │             … │                 … │ … │
        └─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
        """
        current_backend = self._find_backend(use_default=True)
        return current_backend._cached(self)

    def pivot_longer(
        self,
        col: str | s.Selector,
        *,
        names_to: str | Iterable[str] = "name",
        names_pattern: str | re.Pattern = r"(.+)",
        names_transform: Callable[[str], ir.Value]
        | Mapping[str, Callable[[str], ir.Value]]
        | None = None,
        values_to: str = "value",
        values_transform: Callable[[ir.Value], ir.Value] | Deferred | None = None,
    ) -> Table:
        """Transform a table from wider to longer.

        Parameters
        ----------
        col
            String column name or selector.
        names_to
            A string or iterable of strings indicating how to name the new
            pivoted columns.
        names_pattern
            Pattern to use to extract column names from the input. By default
            the entire column name is extracted.
        names_transform
            Function or mapping of a name in `names_to` to a function to
            transform a column name to a value.
        values_to
            Name of the pivoted value column.
        values_transform
            Apply a function to the value column. This can be a lambda or
            deferred expression.

        Returns
        -------
        Table
            Pivoted table

        Examples
        --------
        Basic usage

        >>> import ibis
        >>> import ibis.selectors as s
        >>> from ibis import _
        >>> ibis.options.interactive = True
        >>> relig_income = ibis.examples.relig_income_raw.fetch()
        >>> relig_income
        ┏━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━┓
        ┃ religion                ┃ <$10k ┃ $10-20k ┃ $20-30k ┃ $30-40k ┃ $40-50k ┃ … ┃
        ┡━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━┩
        │ string                  │ int64 │ int64   │ int64   │ int64   │ int64   │ … │
        ├─────────────────────────┼───────┼─────────┼─────────┼─────────┼─────────┼───┤
        │ Agnostic                │    27 │      34 │      60 │      81 │      76 │ … │
        │ Atheist                 │    12 │      27 │      37 │      52 │      35 │ … │
        │ Buddhist                │    27 │      21 │      30 │      34 │      33 │ … │
        │ Catholic                │   418 │     617 │     732 │     670 │     638 │ … │
        │ Don’t know/refused      │    15 │      14 │      15 │      11 │      10 │ … │
        │ Evangelical Prot        │   575 │     869 │    1064 │     982 │     881 │ … │
        │ Hindu                   │     1 │       9 │       7 │       9 │      11 │ … │
        │ Historically Black Prot │   228 │     244 │     236 │     238 │     197 │ … │
        │ Jehovah's Witness       │    20 │      27 │      24 │      24 │      21 │ … │
        │ Jewish                  │    19 │      19 │      25 │      25 │      30 │ … │
        │ …                       │     … │       … │       … │       … │       … │ … │
        └─────────────────────────┴───────┴─────────┴─────────┴─────────┴─────────┴───┘

        Here we convert column names not matching the selector for the `religion` column
        and convert those names into values

        >>> relig_income.pivot_longer(~s.c("religion"), names_to="income", values_to="count")
        ┏━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┓
        ┃ religion ┃ income             ┃ count ┃
        ┡━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━╇━━━━━━━┩
        │ string   │ string             │ int64 │
        ├──────────┼────────────────────┼───────┤
        │ Agnostic │ <$10k              │    27 │
        │ Agnostic │ $10-20k            │    34 │
        │ Agnostic │ $20-30k            │    60 │
        │ Agnostic │ $30-40k            │    81 │
        │ Agnostic │ $40-50k            │    76 │
        │ Agnostic │ $50-75k            │   137 │
        │ Agnostic │ $75-100k           │   122 │
        │ Agnostic │ $100-150k          │   109 │
        │ Agnostic │ >150k              │    84 │
        │ Agnostic │ Don't know/refused │    96 │
        │ …        │ …                  │     … │
        └──────────┴────────────────────┴───────┘

        Similarly for a different example dataset, we convert names to values
        but using a different selector and the default `values_to` value.

        >>> world_bank_pop = ibis.examples.world_bank_pop_raw.fetch()
        >>> world_bank_pop.head()
        ┏━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━┓
        ┃ country ┃ indicator   ┃ 2000         ┃ 2001         ┃ 2002         ┃ … ┃
        ┡━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━┩
        │ string  │ string      │ float64      │ float64      │ float64      │ … │
        ├─────────┼─────────────┼──────────────┼──────────────┼──────────────┼───┤
        │ ABW     │ SP.URB.TOTL │ 4.244400e+04 │ 4.304800e+04 │ 4.367000e+04 │ … │
        │ ABW     │ SP.URB.GROW │ 1.182632e+00 │ 1.413021e+00 │ 1.434560e+00 │ … │
        │ ABW     │ SP.POP.TOTL │ 9.085300e+04 │ 9.289800e+04 │ 9.499200e+04 │ … │
        │ ABW     │ SP.POP.GROW │ 2.055027e+00 │ 2.225930e+00 │ 2.229056e+00 │ … │
        │ AFG     │ SP.URB.TOTL │ 4.436299e+06 │ 4.648055e+06 │ 4.892951e+06 │ … │
        └─────────┴─────────────┴──────────────┴──────────────┴──────────────┴───┘
        >>> world_bank_pop.pivot_longer(s.matches(r"\\d{4}"), names_to="year").head()
        ┏━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━┓
        ┃ country ┃ indicator   ┃ year   ┃ value   ┃
        ┡━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━┩
        │ string  │ string      │ string │ float64 │
        ├─────────┼─────────────┼────────┼─────────┤
        │ ABW     │ SP.URB.TOTL │ 2000   │ 42444.0 │
        │ ABW     │ SP.URB.TOTL │ 2001   │ 43048.0 │
        │ ABW     │ SP.URB.TOTL │ 2002   │ 43670.0 │
        │ ABW     │ SP.URB.TOTL │ 2003   │ 44246.0 │
        │ ABW     │ SP.URB.TOTL │ 2004   │ 44669.0 │
        └─────────┴─────────────┴────────┴─────────┘

        `pivot_longer` has some preprocessing capabiltiies like stripping a prefix and applying
        a function to column names

        >>> billboard = ibis.examples.billboard.fetch()
        >>> billboard
        ┏━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━┓
        ┃ artist         ┃ track                   ┃ date_entered ┃ wk1   ┃ wk2   ┃ … ┃
        ┡━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━┩
        │ string         │ string                  │ date         │ int64 │ int64 │ … │
        ├────────────────┼─────────────────────────┼──────────────┼───────┼───────┼───┤
        │ 2 Pac          │ Baby Don't Cry (Keep... │ 2000-02-26   │    87 │    82 │ … │
        │ 2Ge+her        │ The Hardest Part Of ... │ 2000-09-02   │    91 │    87 │ … │
        │ 3 Doors Down   │ Kryptonite              │ 2000-04-08   │    81 │    70 │ … │
        │ 3 Doors Down   │ Loser                   │ 2000-10-21   │    76 │    76 │ … │
        │ 504 Boyz       │ Wobble Wobble           │ 2000-04-15   │    57 │    34 │ … │
        │ 98^0           │ Give Me Just One Nig... │ 2000-08-19   │    51 │    39 │ … │
        │ A*Teens        │ Dancing Queen           │ 2000-07-08   │    97 │    97 │ … │
        │ Aaliyah        │ I Don't Wanna           │ 2000-01-29   │    84 │    62 │ … │
        │ Aaliyah        │ Try Again               │ 2000-03-18   │    59 │    53 │ … │
        │ Adams, Yolanda │ Open My Heart           │ 2000-08-26   │    76 │    76 │ … │
        │ …              │ …                       │ …            │     … │     … │ … │
        └────────────────┴─────────────────────────┴──────────────┴───────┴───────┴───┘
        >>> billboard.pivot_longer(
        ...     s.startswith("wk"),
        ...     names_to="week",
        ...     names_pattern=r"wk(.+)",
        ...     names_transform=int,
        ...     values_to="rank",
        ...     values_transform=_.cast("int"),
        ... ).dropna("rank")
        ┏━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━┓
        ┃ artist  ┃ track                   ┃ date_entered ┃ week ┃ rank  ┃
        ┡━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━┩
        │ string  │ string                  │ date         │ int8 │ int64 │
        ├─────────┼─────────────────────────┼──────────────┼──────┼───────┤
        │ 2 Pac   │ Baby Don't Cry (Keep... │ 2000-02-26   │    1 │    87 │
        │ 2 Pac   │ Baby Don't Cry (Keep... │ 2000-02-26   │    2 │    82 │
        │ 2 Pac   │ Baby Don't Cry (Keep... │ 2000-02-26   │    3 │    72 │
        │ 2 Pac   │ Baby Don't Cry (Keep... │ 2000-02-26   │    4 │    77 │
        │ 2 Pac   │ Baby Don't Cry (Keep... │ 2000-02-26   │    5 │    87 │
        │ 2 Pac   │ Baby Don't Cry (Keep... │ 2000-02-26   │    6 │    94 │
        │ 2 Pac   │ Baby Don't Cry (Keep... │ 2000-02-26   │    7 │    99 │
        │ 2Ge+her │ The Hardest Part Of ... │ 2000-09-02   │    1 │    91 │
        │ 2Ge+her │ The Hardest Part Of ... │ 2000-09-02   │    2 │    87 │
        │ 2Ge+her │ The Hardest Part Of ... │ 2000-09-02   │    3 │    92 │
        │ …       │ …                       │ …            │    … │     … │
        └─────────┴─────────────────────────┴──────────────┴──────┴───────┘

        You can use regular expression capture groups to extract multiple
        variables stored in column names

        >>> who = ibis.examples.who.fetch()
        >>> who
        ┏━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━┓
        ┃ country     ┃ iso2   ┃ iso3   ┃ year  ┃ new_sp_m014 ┃ new_sp_m1524 ┃ … ┃
        ┡━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━┩
        │ string      │ string │ string │ int64 │ int64       │ int64        │ … │
        ├─────────────┼────────┼────────┼───────┼─────────────┼──────────────┼───┤
        │ Afghanistan │ AF     │ AFG    │  1980 │        NULL │         NULL │ … │
        │ Afghanistan │ AF     │ AFG    │  1981 │        NULL │         NULL │ … │
        │ Afghanistan │ AF     │ AFG    │  1982 │        NULL │         NULL │ … │
        │ Afghanistan │ AF     │ AFG    │  1983 │        NULL │         NULL │ … │
        │ Afghanistan │ AF     │ AFG    │  1984 │        NULL │         NULL │ … │
        │ Afghanistan │ AF     │ AFG    │  1985 │        NULL │         NULL │ … │
        │ Afghanistan │ AF     │ AFG    │  1986 │        NULL │         NULL │ … │
        │ Afghanistan │ AF     │ AFG    │  1987 │        NULL │         NULL │ … │
        │ Afghanistan │ AF     │ AFG    │  1988 │        NULL │         NULL │ … │
        │ Afghanistan │ AF     │ AFG    │  1989 │        NULL │         NULL │ … │
        │ …           │ …      │ …      │     … │           … │            … │ … │
        └─────────────┴────────┴────────┴───────┴─────────────┴──────────────┴───┘
        >>> len(who.columns)
        60
        >>> who.pivot_longer(
        ...     s.r["new_sp_m014":"newrel_f65"],
        ...     names_to=["diagnosis", "gender", "age"],
        ...     names_pattern="new_?(.*)_(.)(.*)",
        ...     values_to="count",
        ... )
        ┏━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━┓
        ┃ country     ┃ iso2   ┃ iso3   ┃ year  ┃ diagnosis ┃ gender ┃ age    ┃ count ┃
        ┡━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━┩
        │ string      │ string │ string │ int64 │ string    │ string │ string │ int64 │
        ├─────────────┼────────┼────────┼───────┼───────────┼────────┼────────┼───────┤
        │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ m      │ 014    │  NULL │
        │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ m      │ 1524   │  NULL │
        │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ m      │ 2534   │  NULL │
        │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ m      │ 3544   │  NULL │
        │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ m      │ 4554   │  NULL │
        │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ m      │ 5564   │  NULL │
        │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ m      │ 65     │  NULL │
        │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ f      │ 014    │  NULL │
        │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ f      │ 1524   │  NULL │
        │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ f      │ 2534   │  NULL │
        │ …           │ …      │ …      │     … │ …         │ …      │ …      │     … │
        └─────────────┴────────┴────────┴───────┴───────────┴────────┴────────┴───────┘

        `names_transform` is flexible, and can be:

            1. A mapping of one or more names in `names_to` to callable
            2. A callable that will be applied to every name

        Let's recode gender and age to numeric values using a mapping

        >>> who.pivot_longer(
        ...     s.r["new_sp_m014":"newrel_f65"],
        ...     names_to=["diagnosis", "gender", "age"],
        ...     names_pattern="new_?(.*)_(.)(.*)",
        ...     names_transform=dict(
        ...         gender={"m": 1, "f": 2}.get,
        ...         age=dict(zip(["014", "1524", "2534", "3544", "4554", "5564", "65"], range(7))).get,
        ...     ),
        ...     values_to="count",
        ... )
        ┏━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━┳━━━━━━┳━━━━━━━┓
        ┃ country     ┃ iso2   ┃ iso3   ┃ year  ┃ diagnosis ┃ gender ┃ age  ┃ count ┃
        ┡━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━╇━━━━━━╇━━━━━━━┩
        │ string      │ string │ string │ int64 │ string    │ int8   │ int8 │ int64 │
        ├─────────────┼────────┼────────┼───────┼───────────┼────────┼──────┼───────┤
        │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      1 │    0 │  NULL │
        │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      1 │    1 │  NULL │
        │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      1 │    2 │  NULL │
        │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      1 │    3 │  NULL │
        │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      1 │    4 │  NULL │
        │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      1 │    5 │  NULL │
        │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      1 │    6 │  NULL │
        │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      2 │    0 │  NULL │
        │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      2 │    1 │  NULL │
        │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      2 │    2 │  NULL │
        │ …           │ …      │ …      │     … │ …         │      … │    … │     … │
        └─────────────┴────────┴────────┴───────┴───────────┴────────┴──────┴───────┘

        The number of match groups in `names_pattern` must match the length of `names_to`

        >>> who.pivot_longer(
        ...     s.r["new_sp_m014":"newrel_f65"],
        ...     names_to=["diagnosis", "gender", "age"],
        ...     names_pattern="new_?(.*)_.(.*)",
        ... )
        Traceback (most recent call last):
          ...
        ibis.common.exceptions.IbisInputError: Number of match groups in `names_pattern` ...

        `names_transform` must be a mapping or callable

        >>> who.pivot_longer(s.r["new_sp_m014":"newrel_f65"], names_transform="upper")
        Traceback (most recent call last):
          ...
        ibis.common.exceptions.IbisTypeError: ... Got <class 'str'>
        """
        import ibis.selectors as s

        pivot_sel = s.c(col) if isinstance(col, str) else col

        pivot_cols = pivot_sel.expand(self)
        if not pivot_cols:
            # TODO: improve the repr of selectors
            raise com.IbisInputError("Selector returned no columns to pivot on")

        names_to = util.promote_list(names_to)

        names_pattern = re.compile(names_pattern)
        if (ngroups := names_pattern.groups) != (nnames := len(names_to)):
            raise com.IbisInputError(
                f"Number of match groups in `names_pattern`"
                f"{names_pattern.pattern!r} ({ngroups:d} groups) doesn't "
                f"match the length of `names_to` {names_to} (length {nnames:d})"
            )

        if names_transform is None:
            names_transform = dict.fromkeys(names_to, toolz.identity)
        elif not isinstance(names_transform, Mapping):
            if callable(names_transform):
                names_transform = dict.fromkeys(names_to, names_transform)
            else:
                raise com.IbisTypeError(
                    f"`names_transform` must be a mapping or callable. Got {type(names_transform)}"
                )

        for name in names_to:
            names_transform.setdefault(name, toolz.identity)

        if values_transform is None:
            values_transform = toolz.identity
        elif isinstance(values_transform, Deferred):
            values_transform = values_transform.resolve

        pieces = []

        for pivot_col in pivot_cols:
            col_name = pivot_col.get_name()
            match_result = names_pattern.match(col_name)
            row = {
                name: names_transform[name](value)
                for name, value in zip(names_to, match_result.groups())
            }
            row[values_to] = values_transform(pivot_col)
            pieces.append(ibis.struct(row))

        # nest into an array of structs to zip unnests together
        pieces = ibis.array(pieces)

        return self.select(~pivot_sel, __pivoted__=pieces.unnest()).unpack(
            "__pivoted__"
        )

    @util.experimental
    def pivot_wider(
        self,
        *,
        id_cols: s.Selector | None = None,
        names_from: str | Iterable[str] | s.Selector = "name",
        names_prefix: str = "",
        names_sep: str = "_",
        names_sort: bool = False,
        names: Iterable[str] | None = None,
        values_from: str | Iterable[str] | s.Selector = "value",
        values_fill: int | float | str | ir.Scalar | None = None,
        values_agg: str | Callable[[ir.Value], ir.Scalar] | Deferred = "arbitrary",
    ):
        """Pivot a table to a wider format.

        Parameters
        ----------
        id_cols
            A set of columns that uniquely identify each observation.
        names_from
            An argument describing which column or columns to use to get the
            name of the output columns.
        names_prefix
            String added to the start of every column name.
        names_sep
            If `names_from` or `values_from` contains multiple columns, this
            argument will be used to join their values together into a single
            string to use as a column name.
        names_sort
            If [`True`][True] columns are sorted. If [`False`][False] column
            names are ordered by appearance.
        names
            An explicit sequence of values to look for in columns matching
            `names_from`.

            * When this value is `None`, the values will be computed from
              `names_from`.
            * When this value is not `None`, each element's length must match
              the length of `names_from`.

            See examples below for more detail.
        values_from
            An argument describing which column or columns to get the cell
            values from.
        values_fill
            A scalar value that specifies what each value should be filled with
            when missing.
        values_agg
            A function applied to the value in each cell in the output.

        Returns
        -------
        Table
            Wider pivoted table

        Examples
        --------
        >>> import ibis
        >>> import ibis.selectors as s
        >>> from ibis import _
        >>> ibis.options.interactive = True

        Basic usage

        >>> fish_encounters = ibis.examples.fish_encounters.fetch()
        >>> fish_encounters
        ┏━━━━━━━┳━━━━━━━━━┳━━━━━━━┓
        ┃ fish  ┃ station ┃ seen  ┃
        ┡━━━━━━━╇━━━━━━━━━╇━━━━━━━┩
        │ int64 │ string  │ int64 │
        ├───────┼─────────┼───────┤
        │  4842 │ Release │     1 │
        │  4842 │ I80_1   │     1 │
        │  4842 │ Lisbon  │     1 │
        │  4842 │ Rstr    │     1 │
        │  4842 │ Base_TD │     1 │
        │  4842 │ BCE     │     1 │
        │  4842 │ BCW     │     1 │
        │  4842 │ BCE2    │     1 │
        │  4842 │ BCW2    │     1 │
        │  4842 │ MAE     │     1 │
        │     … │ …       │     … │
        └───────┴─────────┴───────┘
        >>> fish_encounters.pivot_wider(names_from="station", values_from="seen")
        ┏━━━━━━━┳━━━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━┓
        ┃ fish  ┃ Release ┃ I80_1 ┃ Lisbon ┃ Rstr  ┃ Base_TD ┃ BCE   ┃ BCW   ┃ … ┃
        ┡━━━━━━━╇━━━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━┩
        │ int64 │ int64   │ int64 │ int64  │ int64 │ int64   │ int64 │ int64 │ … │
        ├───────┼─────────┼───────┼────────┼───────┼─────────┼───────┼───────┼───┤
        │  4842 │       1 │     1 │      1 │     1 │       1 │     1 │     1 │ … │
        │  4843 │       1 │     1 │      1 │     1 │       1 │     1 │     1 │ … │
        │  4844 │       1 │     1 │      1 │     1 │       1 │     1 │     1 │ … │
        │  4845 │       1 │     1 │      1 │     1 │       1 │  NULL │  NULL │ … │
        │  4847 │       1 │     1 │      1 │  NULL │    NULL │  NULL │  NULL │ … │
        │  4848 │       1 │     1 │      1 │     1 │    NULL │  NULL │  NULL │ … │
        │  4849 │       1 │     1 │   NULL │  NULL │    NULL │  NULL │  NULL │ … │
        │  4850 │       1 │     1 │   NULL │     1 │       1 │     1 │     1 │ … │
        │  4851 │       1 │     1 │   NULL │  NULL │    NULL │  NULL │  NULL │ … │
        │  4854 │       1 │     1 │   NULL │  NULL │    NULL │  NULL │  NULL │ … │
        │     … │       … │     … │      … │     … │       … │     … │     … │ … │
        └───────┴─────────┴───────┴────────┴───────┴─────────┴───────┴───────┴───┘

        Fill missing pivoted values using `values_fill`

        >>> fish_encounters.pivot_wider(names_from="station", values_from="seen", values_fill=0)
        ┏━━━━━━━┳━━━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━┓
        ┃ fish  ┃ Release ┃ I80_1 ┃ Lisbon ┃ Rstr  ┃ Base_TD ┃ BCE   ┃ BCW   ┃ … ┃
        ┡━━━━━━━╇━━━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━┩
        │ int64 │ int64   │ int64 │ int64  │ int64 │ int64   │ int64 │ int64 │ … │
        ├───────┼─────────┼───────┼────────┼───────┼─────────┼───────┼───────┼───┤
        │  4842 │       1 │     1 │      1 │     1 │       1 │     1 │     1 │ … │
        │  4843 │       1 │     1 │      1 │     1 │       1 │     1 │     1 │ … │
        │  4844 │       1 │     1 │      1 │     1 │       1 │     1 │     1 │ … │
        │  4845 │       1 │     1 │      1 │     1 │       1 │     0 │     0 │ … │
        │  4847 │       1 │     1 │      1 │     0 │       0 │     0 │     0 │ … │
        │  4848 │       1 │     1 │      1 │     1 │       0 │     0 │     0 │ … │
        │  4849 │       1 │     1 │      0 │     0 │       0 │     0 │     0 │ … │
        │  4850 │       1 │     1 │      0 │     1 │       1 │     1 │     1 │ … │
        │  4851 │       1 │     1 │      0 │     0 │       0 │     0 │     0 │ … │
        │  4854 │       1 │     1 │      0 │     0 │       0 │     0 │     0 │ … │
        │     … │       … │     … │      … │     … │       … │     … │     … │ … │
        └───────┴─────────┴───────┴────────┴───────┴─────────┴───────┴───────┴───┘

        Compute multiple values columns

        >>> us_rent_income = ibis.examples.us_rent_income.fetch()
        >>> us_rent_income
        ┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━┓
        ┃ geoid  ┃ name       ┃ variable ┃ estimate ┃ moe   ┃
        ┡━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━┩
        │ string │ string     │ string   │ int64    │ int64 │
        ├────────┼────────────┼──────────┼──────────┼───────┤
        │ 01     │ Alabama    │ income   │    24476 │   136 │
        │ 01     │ Alabama    │ rent     │      747 │     3 │
        │ 02     │ Alaska     │ income   │    32940 │   508 │
        │ 02     │ Alaska     │ rent     │     1200 │    13 │
        │ 04     │ Arizona    │ income   │    27517 │   148 │
        │ 04     │ Arizona    │ rent     │      972 │     4 │
        │ 05     │ Arkansas   │ income   │    23789 │   165 │
        │ 05     │ Arkansas   │ rent     │      709 │     5 │
        │ 06     │ California │ income   │    29454 │   109 │
        │ 06     │ California │ rent     │     1358 │     3 │
        │ …      │ …          │ …        │        … │     … │
        └────────┴────────────┴──────────┴──────────┴───────┘
        >>> us_rent_income.pivot_wider(names_from="variable", values_from=["estimate", "moe"])
        ┏━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━┓
        ┃ geoid  ┃ name                 ┃ estimate_income ┃ moe_income ┃ … ┃
        ┡━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━┩
        │ string │ string               │ int64           │ int64      │ … │
        ├────────┼──────────────────────┼─────────────────┼────────────┼───┤
        │ 01     │ Alabama              │           24476 │        136 │ … │
        │ 02     │ Alaska               │           32940 │        508 │ … │
        │ 04     │ Arizona              │           27517 │        148 │ … │
        │ 05     │ Arkansas             │           23789 │        165 │ … │
        │ 06     │ California           │           29454 │        109 │ … │
        │ 08     │ Colorado             │           32401 │        109 │ … │
        │ 09     │ Connecticut          │           35326 │        195 │ … │
        │ 10     │ Delaware             │           31560 │        247 │ … │
        │ 11     │ District of Columbia │           43198 │        681 │ … │
        │ 12     │ Florida              │           25952 │         70 │ … │
        │ …      │ …                    │               … │          … │ … │
        └────────┴──────────────────────┴─────────────────┴────────────┴───┘

        The column name separator can be changed using the `names_sep` parameter

        >>> us_rent_income.pivot_wider(
        ...     names_from="variable",
        ...     names_sep=".",
        ...     values_from=s.c("estimate", "moe"),
        ... )
        ┏━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━┓
        ┃ geoid  ┃ name                 ┃ estimate.income ┃ moe.income ┃ … ┃
        ┡━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━┩
        │ string │ string               │ int64           │ int64      │ … │
        ├────────┼──────────────────────┼─────────────────┼────────────┼───┤
        │ 01     │ Alabama              │           24476 │        136 │ … │
        │ 02     │ Alaska               │           32940 │        508 │ … │
        │ 04     │ Arizona              │           27517 │        148 │ … │
        │ 05     │ Arkansas             │           23789 │        165 │ … │
        │ 06     │ California           │           29454 │        109 │ … │
        │ 08     │ Colorado             │           32401 │        109 │ … │
        │ 09     │ Connecticut          │           35326 │        195 │ … │
        │ 10     │ Delaware             │           31560 │        247 │ … │
        │ 11     │ District of Columbia │           43198 │        681 │ … │
        │ 12     │ Florida              │           25952 │         70 │ … │
        │ …      │ …                    │               … │          … │ … │
        └────────┴──────────────────────┴─────────────────┴────────────┴───┘

        Supply an alternative function to summarize values

        >>> warpbreaks = ibis.examples.warpbreaks.fetch().select("wool", "tension", "breaks")
        >>> warpbreaks
        ┏━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┓
        ┃ wool   ┃ tension ┃ breaks ┃
        ┡━━━━━━━━╇━━━━━━━━━╇━━━━━━━━┩
        │ string │ string  │ int64  │
        ├────────┼─────────┼────────┤
        │ A      │ L       │     26 │
        │ A      │ L       │     30 │
        │ A      │ L       │     54 │
        │ A      │ L       │     25 │
        │ A      │ L       │     70 │
        │ A      │ L       │     52 │
        │ A      │ L       │     51 │
        │ A      │ L       │     26 │
        │ A      │ L       │     67 │
        │ A      │ M       │     18 │
        │ …      │ …       │      … │
        └────────┴─────────┴────────┘
        >>> warpbreaks.pivot_wider(names_from="wool", values_from="breaks", values_agg="mean")
        ┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━┓
        ┃ tension ┃ A         ┃ B         ┃
        ┡━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━┩
        │ string  │ float64   │ float64   │
        ├─────────┼───────────┼───────────┤
        │ L       │ 44.555556 │ 28.222222 │
        │ M       │ 24.000000 │ 28.777778 │
        │ H       │ 24.555556 │ 18.777778 │
        └─────────┴───────────┴───────────┘

        Passing `Deferred` objects to `values_agg` is supported

        >>> warpbreaks.pivot_wider(
        ...     names_from="tension",
        ...     values_from="breaks",
        ...     values_agg=_.sum(),
        ... )
        ┏━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━┓
        ┃ wool   ┃ L     ┃ M     ┃ H     ┃
        ┡━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━━━━━┩
        │ string │ int64 │ int64 │ int64 │
        ├────────┼───────┼───────┼───────┤
        │ A      │   401 │   216 │   221 │
        │ B      │   254 │   259 │   169 │
        └────────┴───────┴───────┴───────┘

        Use a custom aggregate function

        >>> warpbreaks.pivot_wider(
        ...     names_from="wool",
        ...     values_from="breaks",
        ...     values_agg=lambda col: col.std() / col.mean(),
        ... )
        ┏━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┓
        ┃ tension ┃ A        ┃ B        ┃
        ┡━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━┩
        │ string  │ float64  │ float64  │
        ├─────────┼──────────┼──────────┤
        │ L       │ 0.406183 │ 0.349325 │
        │ M       │ 0.360844 │ 0.327719 │
        │ H       │ 0.418344 │ 0.260590 │
        └─────────┴──────────┴──────────┘

        Generate some random data, setting the random seed for reproducibility

        >>> import random
        >>> random.seed(0)
        >>> raw = ibis.memtable(
        ...     [
        ...         dict(
        ...             product=product,
        ...             country=country,
        ...             year=year,
        ...             production=random.random(),
        ...         )
        ...         for product in "AB"
        ...         for country in ["AI", "EI"]
        ...         for year in range(2000, 2015)
        ...     ]
        ... )
        >>> production = raw.filter(
        ...     ((_.product == "A") & (_.country == "AI")) | (_.product == "B")
        ... )
        >>> production
        ┏━━━━━━━━━┳━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━┓
        ┃ product ┃ country ┃ year  ┃ production ┃
        ┡━━━━━━━━━╇━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━┩
        │ string  │ string  │ int64 │ float64    │
        ├─────────┼─────────┼───────┼────────────┤
        │ B       │ AI      │  2000 │   0.477010 │
        │ B       │ AI      │  2001 │   0.865310 │
        │ B       │ AI      │  2002 │   0.260492 │
        │ B       │ AI      │  2003 │   0.805028 │
        │ B       │ AI      │  2004 │   0.548699 │
        │ B       │ AI      │  2005 │   0.014042 │
        │ B       │ AI      │  2006 │   0.719705 │
        │ B       │ AI      │  2007 │   0.398824 │
        │ B       │ AI      │  2008 │   0.824845 │
        │ B       │ AI      │  2009 │   0.668153 │
        │ …       │ …       │     … │          … │
        └─────────┴─────────┴───────┴────────────┘

        Pivoting with multiple name columns

        >>> production.pivot_wider(
        ...     names_from=["product", "country"],
        ...     values_from="production",
        ... )
        ┏━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┓
        ┃ year  ┃ B_AI     ┃ B_EI     ┃ A_AI     ┃
        ┡━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━┩
        │ int64 │ float64  │ float64  │ float64  │
        ├───────┼──────────┼──────────┼──────────┤
        │  2000 │ 0.477010 │ 0.870471 │ 0.844422 │
        │  2001 │ 0.865310 │ 0.191067 │ 0.757954 │
        │  2002 │ 0.260492 │ 0.567511 │ 0.420572 │
        │  2003 │ 0.805028 │ 0.238616 │ 0.258917 │
        │  2004 │ 0.548699 │ 0.967540 │ 0.511275 │
        │  2005 │ 0.014042 │ 0.803179 │ 0.404934 │
        │  2006 │ 0.719705 │ 0.447970 │ 0.783799 │
        │  2007 │ 0.398824 │ 0.080446 │ 0.303313 │
        │  2008 │ 0.824845 │ 0.320055 │ 0.476597 │
        │  2009 │ 0.668153 │ 0.507941 │ 0.583382 │
        │     … │        … │        … │        … │
        └───────┴──────────┴──────────┴──────────┘

        Select a subset of names. This call incurs no computation when
        constructing the expression.

        >>> production.pivot_wider(
        ...     names_from=["product", "country"],
        ...     names=[("A", "AI"), ("B", "AI")],
        ...     values_from="production",
        ... )
        ┏━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┓
        ┃ year  ┃ A_AI     ┃ B_AI     ┃
        ┡━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━┩
        │ int64 │ float64  │ float64  │
        ├───────┼──────────┼──────────┤
        │  2000 │ 0.844422 │ 0.477010 │
        │  2001 │ 0.757954 │ 0.865310 │
        │  2002 │ 0.420572 │ 0.260492 │
        │  2003 │ 0.258917 │ 0.805028 │
        │  2004 │ 0.511275 │ 0.548699 │
        │  2005 │ 0.404934 │ 0.014042 │
        │  2006 │ 0.783799 │ 0.719705 │
        │  2007 │ 0.303313 │ 0.398824 │
        │  2008 │ 0.476597 │ 0.824845 │
        │  2009 │ 0.583382 │ 0.668153 │
        │     … │        … │        … │
        └───────┴──────────┴──────────┘

        Sort the new columns' names

        >>> production.pivot_wider(
        ...     names_from=["product", "country"],
        ...     values_from="production",
        ...     names_sort=True,
        ... )
        ┏━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┓
        ┃ year  ┃ A_AI     ┃ B_AI     ┃ B_EI     ┃
        ┡━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━┩
        │ int64 │ float64  │ float64  │ float64  │
        ├───────┼──────────┼──────────┼──────────┤
        │  2000 │ 0.844422 │ 0.477010 │ 0.870471 │
        │  2001 │ 0.757954 │ 0.865310 │ 0.191067 │
        │  2002 │ 0.420572 │ 0.260492 │ 0.567511 │
        │  2003 │ 0.258917 │ 0.805028 │ 0.238616 │
        │  2004 │ 0.511275 │ 0.548699 │ 0.967540 │
        │  2005 │ 0.404934 │ 0.014042 │ 0.803179 │
        │  2006 │ 0.783799 │ 0.719705 │ 0.447970 │
        │  2007 │ 0.303313 │ 0.398824 │ 0.080446 │
        │  2008 │ 0.476597 │ 0.824845 │ 0.320055 │
        │  2009 │ 0.583382 │ 0.668153 │ 0.507941 │
        │     … │        … │        … │        … │
        └───────┴──────────┴──────────┴──────────┘
        """
        import pandas as pd
        import ibis.selectors as s
        import ibis.expr.analysis as an
        from ibis import _

        orig_names_from = util.promote_list(names_from)

        names_from = s.any_of(*map(s._to_selector, orig_names_from))
        values_from = s.any_of(*map(s._to_selector, util.promote_list(values_from)))

        if id_cols is None:
            id_cols = ~(names_from | values_from)
        else:
            id_cols = s._to_selector(id_cols)

        if isinstance(values_agg, str):
            values_agg = operator.methodcaller(values_agg)
        elif isinstance(values_agg, Deferred):
            values_agg = values_agg.resolve

        if names is None:
            # no names provided, compute them from the data
            names = self.select(names_from).distinct().execute()
        else:
            if not (columns := [col.get_name() for col in names_from.expand(self)]):
                raise com.IbisInputError(
                    f"No matching names columns in `names_from`: {orig_names_from}"
                )
            names = pd.DataFrame(list(map(util.promote_list, names)), columns=columns)

        if names_sort:
            names = names.sort_values(by=names.columns.tolist())

        values_cols = values_from.expand(self)
        more_than_one_value = len(values_cols) > 1
        aggs = {}

        names_cols_exprs = [self[col] for col in names.columns]

        for keys in names.itertuples(index=False):
            where = ibis.and_(*map(operator.eq, names_cols_exprs, keys))

            for values_col in values_cols:
                arg = values_agg(values_col)

                # add in the where clause to filter the appropriate values
                # in/out
                #
                # this allows users to write the aggregate without having to deal with
                # the filter themselves
                existing_aggs = an.find_toplevel_aggs(arg.op())
                subs = {
                    agg: agg.copy(
                        where=(
                            where
                            if (existing := agg.where) is None
                            else where & existing
                        )
                    )
                    for agg in existing_aggs
                }
                arg = an.sub_for(arg.op(), subs).to_expr()

                # build the components of the group by key
                key_components = (
                    # user provided prefix
                    names_prefix,
                    # include the `values` column name if there's more than one
                    # `values` column
                    values_col.get_name() * more_than_one_value,
                    # values computed from `names`/`names_from`
                    *keys,
                )
                key = names_sep.join(filter(None, key_components))
                aggs[key] = arg if values_fill is None else arg.coalesce(values_fill)

        return self.group_by(id_cols).aggregate(**aggs)

Attributes

columns: list[str] property

The list of columns 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']

Functions

aggregate(metrics=None, by=None, having=None, **kwargs)

Aggregate a table with a given set of reductions grouping by by.

Parameters:

Name Type Description Default
metrics Sequence[ir.Scalar] | None

Aggregate expressions. These can be any scalar-producing expression, including aggregation functions like sum or literal values like ibis.literal(1).

None
by Sequence[ir.Value] | None

Grouping expressions.

None
having Sequence[ir.BooleanValue] | None

Post-aggregation filters. The shape requirements are the same metrics, but the output type for having is boolean.

Expressions like x is None return bool and will not generate a SQL comparison to NULL

None
kwargs ir.Value

Named aggregate expressions

{}

Returns:

Type Description
Table

An aggregate 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.aggregate(by=["fruit"], total_cost=_.price.sum(), avg_cost=_.price.mean(), having=_.price.sum() < 0.5)
┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━┓
┃ fruit  ┃ total_cost ┃ avg_cost ┃
┡━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━┩
│ string │ float64    │ float64  │
├────────┼────────────┼──────────┤
│ banana │       0.25 │     0.25 │
│ orange │       0.33 │     0.33 │
└────────┴────────────┴──────────┘
Source code in ibis/expr/types/relations.py
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
def aggregate(
    self,
    metrics: Sequence[ir.Scalar] | None = None,
    by: Sequence[ir.Value] | None = None,
    having: Sequence[ir.BooleanValue] | None = None,
    **kwargs: ir.Value,
) -> Table:
    """Aggregate a table with a given set of reductions grouping by `by`.

    Parameters
    ----------
    metrics
        Aggregate expressions. These can be any scalar-producing
        expression, including aggregation functions like `sum` or literal
        values like `ibis.literal(1)`.
    by
        Grouping expressions.
    having
        Post-aggregation filters. The shape requirements are the same
        `metrics`, but the output type for `having` is `boolean`.

        !!! warning "Expressions like `x is None` return `bool` and **will not** generate a SQL comparison to `NULL`"
    kwargs
        Named aggregate expressions

    Returns
    -------
    Table
        An aggregate 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.aggregate(by=["fruit"], total_cost=_.price.sum(), avg_cost=_.price.mean(), having=_.price.sum() < 0.5)
    ┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━┓
    ┃ fruit  ┃ total_cost ┃ avg_cost ┃
    ┡━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━┩
    │ string │ float64    │ float64  │
    ├────────┼────────────┼──────────┤
    │ banana │       0.25 │     0.25 │
    │ orange │       0.33 │     0.33 │
    └────────┴────────────┴──────────┘
    """
    import ibis.expr.analysis as an

    metrics = itertools.chain(
        itertools.chain.from_iterable(
            (
                (_ensure_expr(self, m) for m in metric)
                if isinstance(metric, (list, tuple))
                else util.promote_list(_ensure_expr(self, metric))
            )
            for metric in util.promote_list(metrics)
        ),
        (
            e.name(name)
            for name, expr in kwargs.items()
            for e in util.promote_list(_ensure_expr(self, expr))
        ),
    )

    agg = ops.Aggregation(
        self,
        metrics=list(metrics),
        by=bind_expr(self, util.promote_list(by)),
        having=bind_expr(self, util.promote_list(having)),
    )
    agg = an.simplify_aggregation(agg)

    return agg.to_expr()

alias(alias)

Create a table expression with a specific name alias.

This method is useful for exposing an ibis expression to the underlying backend for use in the Table.sql method.

.alias will create a temporary view

.alias creates a temporary view in the database.

This side effect will be removed in a future version of ibis and is not part of the public API.

Parameters:

Name Type Description Default
alias str

Name of the child expression

required

Returns:

Type Description
Table

An table expression

Examples:

>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.examples.penguins.fetch()
>>> expr = t.alias("pingüinos").sql('SELECT * FROM "pingüinos" LIMIT 5')
>>> expr
┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
┃ 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 │            nan │           nan │              NULL │ … │
│ Adelie  │ Torgersen │           36.7 │          19.3 │               193 │ … │
└─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
Source code in ibis/expr/types/relations.py
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
def alias(self, alias: str) -> ir.Table:
    """Create a table expression with a specific name `alias`.

    This method is useful for exposing an ibis expression to the underlying
    backend for use in the
    [`Table.sql`][ibis.expr.types.relations.Table.sql] method.

    !!! note "`.alias` will create a temporary view"

        `.alias` creates a temporary view in the database.

        This side effect will be removed in a future version of ibis and
        **is not part of the public API**.

    Parameters
    ----------
    alias
        Name of the child expression

    Returns
    -------
    Table
        An table expression

    Examples
    --------
    >>> import ibis
    >>> ibis.options.interactive = True
    >>> t = ibis.examples.penguins.fetch()
    >>> expr = t.alias("pingüinos").sql('SELECT * FROM "pingüinos" LIMIT 5')
    >>> expr
    ┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
    ┃ 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 │            nan │           nan │              NULL │ … │
    │ Adelie  │ Torgersen │           36.7 │          19.3 │               193 │ … │
    └─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
    """
    expr = ops.View(child=self, name=alias).to_expr()

    # NB: calling compile is necessary so that any temporary views are
    # created so that we can infer the schema without executing the entire
    # query
    expr.compile()
    return expr

as_table()

Promote the expression to a table.

This method is a no-op for table expressions.

Returns:

Type Description
Table

A table expression

Examples:

>>> t = ibis.table(dict(a="int"), name="t")
>>> s = t.as_table()
>>> t is s
True
Source code in ibis/expr/types/relations.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
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

asof_join(left, right, predicates=(), by=(), tolerance=None, *, lname='', rname='{name}_right')

Perform an "as-of" join between left and right.

Similar to a left join except that the match is done on nearest key rather than equal keys.

Optionally, match keys with by before joining with predicates.

Parameters:

Name Type Description Default
left Table

Table expression

required
right Table

Table expression

required
predicates str | ir.BooleanColumn | Sequence[str | ir.BooleanColumn]

Join expressions

()
by str | ir.Column | Sequence[str | ir.Column]

column to group by before joining

()
tolerance str | ir.IntervalScalar | None

Amount of time to look behind when joining

None
lname str

A format string to use to rename overlapping columns in the left table (e.g. "left_{name}").

''
rname str

A format string to use to rename overlapping columns in the right table (e.g. "right_{name}").

'{name}_right'

Returns:

Type Description
Table

Table expression

Source code in ibis/expr/types/relations.py
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
def asof_join(
    left: Table,
    right: Table,
    predicates: str | ir.BooleanColumn | Sequence[str | ir.BooleanColumn] = (),
    by: str | ir.Column | Sequence[str | ir.Column] = (),
    tolerance: str | ir.IntervalScalar | None = None,
    *,
    lname: str = "",
    rname: str = "{name}_right",
) -> Table:
    """Perform an "as-of" join between `left` and `right`.

    Similar to a left join except that the match is done on nearest key
    rather than equal keys.

    Optionally, match keys with `by` before joining with `predicates`.

    Parameters
    ----------
    left
        Table expression
    right
        Table expression
    predicates
        Join expressions
    by
        column to group by before joining
    tolerance
        Amount of time to look behind when joining
    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
        Table expression
    """
    op = ops.AsOfJoin(
        left=left,
        right=right,
        predicates=predicates,
        by=by,
        tolerance=tolerance,
    )
    return ops.relations._dedup_join_columns(op.to_expr(), lname=lname, rname=rname)

cache()

Cache the provided expression.

All subsequent operations on the returned expression will be performed on the cached data. Use the with statement to limit the lifetime of a cached table.

This method is idempotent: calling it multiple times in succession will return the same value as the first call.

This method eagerly evaluates the expression prior to caching

Subsequent evaluations will not recompute the expression so method chaining will not incur the overhead of caching more than once.

Returns:

Type Description
Table

Cached table

Examples:

>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.examples.penguins.fetch()
>>> cached_penguins = t.mutate(computation="Heavy Computation").cache()
>>> cached_penguins
┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
┃ 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 │            nan │           nan │              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 │ … │
│ …       │ …         │              … │             … │                 … │ … │
└─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘

Explicit cache cleanup

>>> with t.mutate(computation="Heavy Computation").cache() as cached_penguins:
...     cached_penguins
┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
┃ 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 │            nan │           nan │              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 │ … │
│ …       │ …         │              … │             … │                 … │ … │
└─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
Source code in ibis/expr/types/relations.py
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
def cache(self) -> Table:
    """Cache the provided expression.

    All subsequent operations on the returned expression will be performed
    on the cached data. Use the
    [`with`](https://docs.python.org/3/reference/compound_stmts.html#with)
    statement to limit the lifetime of a cached table.

    This method is idempotent: calling it multiple times in succession will
    return the same value as the first call.

    !!! note "This method eagerly evaluates the expression prior to caching"

        Subsequent evaluations will not recompute the expression so method
        chaining will not incur the overhead of caching more than once.

    Returns
    -------
    Table
        Cached table

    Examples
    --------
    >>> import ibis
    >>> ibis.options.interactive = True
    >>> t = ibis.examples.penguins.fetch()
    >>> cached_penguins = t.mutate(computation="Heavy Computation").cache()
    >>> cached_penguins
    ┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
    ┃ 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 │            nan │           nan │              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 │ … │
    │ …       │ …         │              … │             … │                 … │ … │
    └─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘

    Explicit cache cleanup

    >>> with t.mutate(computation="Heavy Computation").cache() as cached_penguins:
    ...     cached_penguins
    ┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
    ┃ 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 │            nan │           nan │              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 │ … │
    │ …       │ …         │              … │             … │                 … │ … │
    └─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
    """
    current_backend = self._find_backend(use_default=True)
    return current_backend._cached(self)

cast(schema)

Cast the columns of a table.

If you need to cast columns to a single type, use selectors.

Parameters:

Name Type Description Default
schema SupportsSchema

Mapping, schema or iterable of pairs to use for casting

required

Returns:

Type Description
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 │            nan │
│        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 │
│         nan │           NULL │
│      3450.0 │             37 │
└─────────────┴────────────────┘

Columns that are in the input schema but not in the table raise an error

>>> t.cast({"foo": "string"})
Traceback (most recent call last):
    ...
ibis.common.exceptions.IbisError: Cast schema has fields that are not in the table: ['foo']
Source code in ibis/expr/types/relations.py
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
def cast(self, schema: SupportsSchema) -> Table:
    """Cast the columns of a table.

    !!! note "If you need to cast columns to a single type, use [selectors](https://ibis-project.org/blog/selectors/)."

    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 │            nan │
    │        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 │
    │         nan │           NULL │
    │      3450.0 │             37 │
    └─────────────┴────────────────┘

    Columns that are in the input `schema` but not in the table raise an error

    >>> t.cast({"foo": "string"})
    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")

count(where=None)

Compute the number of rows in the table.

Parameters:

Name Type Description Default
where ir.BooleanValue | None

Optional boolean expression to filter rows when counting.

None

Returns:

Type Description
IntegerScalar

Number of rows in the table

Examples:

>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.memtable({"a": ["foo", "bar", "baz"]})
>>> t
┏━━━━━━━━┓
┃ a      ┃
┡━━━━━━━━┩
│ string │
├────────┤
│ foo    │
│ bar    │
│ baz    │
└────────┘
>>> t.count()
3
>>> t.count(t.a != "foo")
2
>>> type(t.count())
<class 'ibis.expr.types.numeric.IntegerScalar'>
Source code in ibis/expr/types/relations.py
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
def count(self, where: ir.BooleanValue | None = None) -> ir.IntegerScalar:
    """Compute the number of rows in the table.

    Parameters
    ----------
    where
        Optional boolean expression to filter rows when counting.

    Returns
    -------
    IntegerScalar
        Number of rows in the table

    Examples
    --------
    >>> import ibis
    >>> ibis.options.interactive = True
    >>> t = ibis.memtable({"a": ["foo", "bar", "baz"]})
    >>> t
    ┏━━━━━━━━┓
    ┃ a      ┃
    ┡━━━━━━━━┩
    │ string │
    ├────────┤
    │ foo    │
    │ bar    │
    │ baz    │
    └────────┘
    >>> t.count()
    3
    >>> t.count(t.a != "foo")
    2
    >>> type(t.count())
    <class 'ibis.expr.types.numeric.IntegerScalar'>
    """
    return ops.CountStar(self, where).to_expr()

cross_join(left, right, *rest, lname='', rname='{name}_right')

Compute the cross join of a sequence of tables.

Parameters:

Name Type Description Default
left Table

Left table

required
right Table

Right table

required
rest Table

Additional tables to cross join

()
lname str

A format string to use to rename overlapping columns in the left table (e.g. "left_{name}").

''
rname str

A format string to use to rename overlapping columns in the right table (e.g. "right_{name}").

'{name}_right'

Returns:

Type Description
Table

Cross join of left, right and rest

Examples:

>>> import ibis
>>> import ibis.selectors as s
>>> from ibis import _
>>> ibis.options.interactive = True
>>> t = ibis.examples.penguins.fetch()
>>> t.count()
344
>>> agg = t.drop("year").agg(s.across(s.numeric(), _.mean()))
>>> expr = t.cross_join(agg)
>>> expr
┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
┃ 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 │            nan │           nan │              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 │ … │
│ …       │ …         │              … │             … │                 … │ … │
└─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
>>> expr.columns
['species',
 'island',
 'bill_length_mm',
 'bill_depth_mm',
 'flipper_length_mm',
 'body_mass_g',
 'sex',
 'year',
 'bill_length_mm_right',
 'bill_depth_mm_right',
 'flipper_length_mm_right',
 'body_mass_g_right']
>>> expr.count()
344
Source code in ibis/expr/types/relations.py
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
def cross_join(
    left: Table,
    right: Table,
    *rest: Table,
    lname: str = "",
    rname: str = "{name}_right",
) -> Table:
    """Compute the cross join of a sequence of tables.

    Parameters
    ----------
    left
        Left table
    right
        Right table
    rest
        Additional tables to cross join
    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
        Cross join of `left`, `right` and `rest`

    Examples
    --------
    >>> import ibis
    >>> import ibis.selectors as s
    >>> from ibis import _
    >>> ibis.options.interactive = True
    >>> t = ibis.examples.penguins.fetch()
    >>> t.count()
    344
    >>> agg = t.drop("year").agg(s.across(s.numeric(), _.mean()))
    >>> expr = t.cross_join(agg)
    >>> expr
    ┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
    ┃ 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 │            nan │           nan │              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 │ … │
    │ …       │ …         │              … │             … │                 … │ … │
    └─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
    >>> expr.columns
    ['species',
     'island',
     'bill_length_mm',
     'bill_depth_mm',
     'flipper_length_mm',
     'body_mass_g',
     'sex',
     'year',
     'bill_length_mm_right',
     'bill_depth_mm_right',
     'flipper_length_mm_right',
     'body_mass_g_right']
    >>> expr.count()
    344
    """
    op = ops.CrossJoin(
        left,
        functools.reduce(Table.cross_join, rest, right),
        [],
    )
    return ops.relations._dedup_join_columns(op.to_expr(), lname=lname, rname=rname)

difference(table, *rest, distinct=True)

Compute the set difference of multiple table expressions.

The input tables must have identical schemas.

Parameters:

Name Type Description Default
table Table

A table expression

required
*rest Table

Additional table expressions

()
distinct bool

Only diff distinct rows not occurring in the calling table

True
See Also

ibis.difference

Returns:

Type Description
Table

The rows present in self that are not present in tables.

Examples:

>>> import ibis
>>> ibis.options.interactive = True
>>> t1 = ibis.memtable({"a": [1, 2]})
>>> t1
┏━━━━━━━┓
┃ a     ┃
┡━━━━━━━┩
│ int64 │
├───────┤
│     1 │
│     2 │
└───────┘
>>> t2 = ibis.memtable({"a": [2, 3]})
>>> t2
┏━━━━━━━┓
┃ a     ┃
┡━━━━━━━┩
│ int64 │
├───────┤
│     2 │
│     3 │
└───────┘
>>> t1.difference(t2)
┏━━━━━━━┓
┃ a     ┃
┡━━━━━━━┩
│ int64 │
├───────┤
│     1 │
└───────┘
Source code in ibis/expr/types/relations.py
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
def difference(self, table: Table, *rest: Table, distinct: bool = True) -> Table:
    """Compute the set difference of multiple table expressions.

    The input tables must have identical schemas.

    Parameters
    ----------
    table:
        A table expression
    *rest:
        Additional table expressions
    distinct
        Only diff distinct rows not occurring in the calling table

    See Also
    --------
    [`ibis.difference`][ibis.difference]

    Returns
    -------
    Table
        The rows present in `self` that are not present in `tables`.

    Examples
    --------
    >>> import ibis
    >>> ibis.options.interactive = True
    >>> t1 = ibis.memtable({"a": [1, 2]})
    >>> t1
    ┏━━━━━━━┓
    ┃ a     ┃
    ┡━━━━━━━┩
    │ int64 │
    ├───────┤
    │     1 │
    │     2 │
    └───────┘
    >>> t2 = ibis.memtable({"a": [2, 3]})
    >>> t2
    ┏━━━━━━━┓
    ┃ a     ┃
    ┡━━━━━━━┩
    │ int64 │
    ├───────┤
    │     2 │
    │     3 │
    └───────┘
    >>> t1.difference(t2)
    ┏━━━━━━━┓
    ┃ a     ┃
    ┡━━━━━━━┩
    │ int64 │
    ├───────┤
    │     1 │
    └───────┘
    """
    node = ops.Difference(self, table, distinct=distinct)
    for table in rest:
        node = ops.Difference(node, table, distinct=distinct)
    return node.to_expr().select(self.columns)

distinct(*, on=None, keep='first')

Return a Table with duplicate rows removed.

Similar to pandas.DataFrame.drop_duplicates().

Some backends do not support keep='last'

Parameters:

Name Type Description Default
on str | Iterable[str] | s.Selector | None

Only consider certain columns for identifying duplicates. By default deduplicate all of the columns.

None
keep Literal['first', 'last'] | None

Determines which duplicates to keep.

  • "first": Drop duplicates except for the first occurrence.
  • "last": Drop duplicates except for the last occurrence.
  • None: Drop all duplicates
'first'

Examples:

>>> import ibis
>>> import ibis.examples as ex
>>> import ibis.selectors as s
>>> ibis.options.interactive = True
>>> t = ex.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 │            nan │           nan │              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 │ … │
│ …       │ …         │              … │             … │                 … │ … │
└─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘

Compute the distinct rows of a subset of columns

>>> t[["species", "island"]].distinct()
┏━━━━━━━━━━━┳━━━━━━━━━━━┓
┃ species   ┃ island    ┃
┡━━━━━━━━━━━╇━━━━━━━━━━━┩
│ string    │ string    │
├───────────┼───────────┤
│ Adelie    │ Torgersen │
│ Adelie    │ Biscoe    │
│ Adelie    │ Dream     │
│ Gentoo    │ Biscoe    │
│ Chinstrap │ Dream     │
└───────────┴───────────┘

Drop all duplicate rows except the first

>>> t.distinct(on=["species", "island"], keep="first")
┏━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━┓
┃ species   ┃ island    ┃ bill_length_mm ┃ bill_depth_… ┃ flipper_length_mm ┃  ┃
┡━━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━┩
│ string    │ string    │ float64        │ float64      │ int64             │  │
├───────────┼───────────┼────────────────┼──────────────┼───────────────────┼──┤
│ Adelie    │ Torgersen │           39.1 │         18.7 │               181 │  │
│ Adelie    │ Biscoe    │           37.8 │         18.3 │               174 │  │
│ Adelie    │ Dream     │           39.5 │         16.7 │               178 │  │
│ Gentoo    │ Biscoe    │           46.1 │         13.2 │               211 │  │
│ Chinstrap │ Dream     │           46.5 │         17.9 │               192 │  │
└───────────┴───────────┴────────────────┴──────────────┴───────────────────┴──┘

Drop all duplicate rows except the last

>>> t.distinct(on=["species", "island"], keep="last")
┏━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━┓
┃ species   ┃ island    ┃ bill_length_mm ┃ bill_depth_… ┃ flipper_length_mm ┃  ┃
┡━━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━┩
│ string    │ string    │ float64        │ float64      │ int64             │  │
├───────────┼───────────┼────────────────┼──────────────┼───────────────────┼──┤
│ Adelie    │ Torgersen │           43.1 │         19.2 │               197 │  │
│ Adelie    │ Biscoe    │           42.7 │         18.3 │               196 │  │
│ Adelie    │ Dream     │           41.5 │         18.5 │               201 │  │
│ Gentoo    │ Biscoe    │           49.9 │         16.1 │               213 │  │
│ Chinstrap │ Dream     │           50.2 │         18.7 │               198 │  │
└───────────┴───────────┴────────────────┴──────────────┴───────────────────┴──┘

Drop all duplicated rows

>>> expr = t.distinct(on=["species", "island", "year", "bill_length_mm"], keep=None)
>>> expr.count()
273
>>> t.count()
344

You can pass selectors to on

>>> t.distinct(on=~s.numeric())
┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
┃ 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 │            nan │           nan │              NULL │ … │
│ Adelie  │ Biscoe    │           37.8 │          18.3 │               174 │ … │
│ Adelie  │ Biscoe    │           37.7 │          18.7 │               180 │ … │
│ Adelie  │ Dream     │           39.5 │          16.7 │               178 │ … │
│ Adelie  │ Dream     │           37.2 │          18.1 │               178 │ … │
│ Adelie  │ Dream     │           37.5 │          18.9 │               179 │ … │
│ Gentoo  │ Biscoe    │           46.1 │          13.2 │               211 │ … │
│ Gentoo  │ Biscoe    │           50.0 │          16.3 │               230 │ … │
│ …       │ …         │              … │             … │                 … │ … │
└─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘

The only valid values of keep are "first", "last" and `None

>>> t.distinct(on="species", keep="second")
Traceback (most recent call last):
  ...
ibis.common.exceptions.IbisError: Invalid value for keep: 'second' ...
Source code in ibis/expr/types/relations.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
def distinct(
    self,
    *,
    on: str | Iterable[str] | s.Selector | None = None,
    keep: Literal["first", "last"] | None = "first",
) -> Table:
    """Return a Table with duplicate rows removed.

    Similar to `pandas.DataFrame.drop_duplicates()`.

    !!! note "Some backends do not support `keep='last'`"

    Parameters
    ----------
    on
        Only consider certain columns for identifying duplicates.
        By default deduplicate all of the columns.
    keep
        Determines which duplicates to keep.

        - `"first"`: Drop duplicates except for the first occurrence.
        - `"last"`: Drop duplicates except for the last occurrence.
        - `None`: Drop all duplicates

    Examples
    --------
    >>> import ibis
    >>> import ibis.examples as ex
    >>> import ibis.selectors as s
    >>> ibis.options.interactive = True
    >>> t = ex.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 │            nan │           nan │              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 │ … │
    │ …       │ …         │              … │             … │                 … │ … │
    └─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘

    Compute the distinct rows of a subset of columns

    >>> t[["species", "island"]].distinct()
    ┏━━━━━━━━━━━┳━━━━━━━━━━━┓
    ┃ species   ┃ island    ┃
    ┡━━━━━━━━━━━╇━━━━━━━━━━━┩
    │ string    │ string    │
    ├───────────┼───────────┤
    │ Adelie    │ Torgersen │
    │ Adelie    │ Biscoe    │
    │ Adelie    │ Dream     │
    │ Gentoo    │ Biscoe    │
    │ Chinstrap │ Dream     │
    └───────────┴───────────┘

    Drop all duplicate rows except the first

    >>> t.distinct(on=["species", "island"], keep="first")
    ┏━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━┓
    ┃ species   ┃ island    ┃ bill_length_mm ┃ bill_depth_… ┃ flipper_length_mm ┃  ┃
    ┡━━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━┩
    │ string    │ string    │ float64        │ float64      │ int64             │  │
    ├───────────┼───────────┼────────────────┼──────────────┼───────────────────┼──┤
    │ Adelie    │ Torgersen │           39.1 │         18.7 │               181 │  │
    │ Adelie    │ Biscoe    │           37.8 │         18.3 │               174 │  │
    │ Adelie    │ Dream     │           39.5 │         16.7 │               178 │  │
    │ Gentoo    │ Biscoe    │           46.1 │         13.2 │               211 │  │
    │ Chinstrap │ Dream     │           46.5 │         17.9 │               192 │  │
    └───────────┴───────────┴────────────────┴──────────────┴───────────────────┴──┘

    Drop all duplicate rows except the last

    >>> t.distinct(on=["species", "island"], keep="last")
    ┏━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━┓
    ┃ species   ┃ island    ┃ bill_length_mm ┃ bill_depth_… ┃ flipper_length_mm ┃  ┃
    ┡━━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━┩
    │ string    │ string    │ float64        │ float64      │ int64             │  │
    ├───────────┼───────────┼────────────────┼──────────────┼───────────────────┼──┤
    │ Adelie    │ Torgersen │           43.1 │         19.2 │               197 │  │
    │ Adelie    │ Biscoe    │           42.7 │         18.3 │               196 │  │
    │ Adelie    │ Dream     │           41.5 │         18.5 │               201 │  │
    │ Gentoo    │ Biscoe    │           49.9 │         16.1 │               213 │  │
    │ Chinstrap │ Dream     │           50.2 │         18.7 │               198 │  │
    └───────────┴───────────┴────────────────┴──────────────┴───────────────────┴──┘

    Drop all duplicated rows

    >>> expr = t.distinct(on=["species", "island", "year", "bill_length_mm"], keep=None)
    >>> expr.count()
    273
    >>> t.count()
    344

    You can pass [`selectors`][ibis.selectors] to `on`

    >>> t.distinct(on=~s.numeric())
    ┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
    ┃ 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 │            nan │           nan │              NULL │ … │
    │ Adelie  │ Biscoe    │           37.8 │          18.3 │               174 │ … │
    │ Adelie  │ Biscoe    │           37.7 │          18.7 │               180 │ … │
    │ Adelie  │ Dream     │           39.5 │          16.7 │               178 │ … │
    │ Adelie  │ Dream     │           37.2 │          18.1 │               178 │ … │
    │ Adelie  │ Dream     │           37.5 │          18.9 │               179 │ … │
    │ Gentoo  │ Biscoe    │           46.1 │          13.2 │               211 │ … │
    │ Gentoo  │ Biscoe    │           50.0 │          16.3 │               230 │ … │
    │ …       │ …         │              … │             … │                 … │ … │
    └─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘

    The only valid values of `keep` are `"first"`, `"last"` and [`None][None]

    >>> t.distinct(on="species", keep="second")
    Traceback (most recent call last):
      ...
    ibis.common.exceptions.IbisError: Invalid value for keep: 'second' ...
    """

    import ibis.selectors as s

    if on is None:
        # dedup everything
        if keep != "first":
            raise com.IbisError(
                f"Only keep='first' (the default) makes sense when deduplicating all columns; got keep={keep!r}"
            )
        return ops.Distinct(self).to_expr()

    if not isinstance(on, s.Selector):
        on = s.c(*util.promote_list(on))

    if keep is None:
        having = lambda t: t.count() == 1
        how = "first"
    elif keep == "first" or keep == "last":
        having = None
        how = keep
    else:
        raise com.IbisError(
            f"Invalid value for `keep`: {keep!r}, must be 'first', 'last' or None"
        )

    aggs = {col.get_name(): col.arbitrary(how=how) for col in (~on).expand(self)}

    gb = self.group_by(on)
    if having is not None:
        gb = gb.having(having)
    res = gb.agg(**aggs)

    assert len(res.columns) == len(self.columns)
    if res.columns != self.columns:
        return res.select(self.columns)
    return res

drop(*fields)

Remove fields from a table.

Parameters:

Name Type Description Default
fields str | Selector

Fields to drop. Strings and selectors are accepted.

()

Returns:

Type Description
Table

A table with all columns matching fields removed.

Examples:

>>> import ibis
>>> 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 │            nan │           nan │              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 │ … │
│ …       │ …         │              … │             … │                 … │ … │
└─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘

Drop one or more columns

>>> t.drop("species").head()
┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
┃ island    ┃ bill_length_mm ┃ bill_depth_mm ┃ flipper_length_mm ┃ … ┃
┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━┩
│ string    │ float64        │ float64       │ int64             │ … │
├───────────┼────────────────┼───────────────┼───────────────────┼───┤
│ Torgersen │           39.1 │          18.7 │               181 │ … │
│ Torgersen │           39.5 │          17.4 │               186 │ … │
│ Torgersen │           40.3 │          18.0 │               195 │ … │
│ Torgersen │            nan │           nan │              NULL │ … │
│ Torgersen │           36.7 │          19.3 │               193 │ … │
└───────────┴────────────────┴───────────────┴───────────────────┴───┘
>>> t.drop("species", "bill_length_mm").head()
┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━┓
┃ island    ┃ bill_depth_mm ┃ flipper_length_mm ┃ body_mass_g ┃ sex    ┃ … ┃
┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━┩
│ string    │ float64       │ int64             │ int64       │ string │ … │
├───────────┼───────────────┼───────────────────┼─────────────┼────────┼───┤
│ Torgersen │          18.7 │               181 │        3750 │ male   │ … │
│ Torgersen │          17.4 │               186 │        3800 │ female │ … │
│ Torgersen │          18.0 │               195 │        3250 │ female │ … │
│ Torgersen │           nan │              NULL │        NULL │ NULL   │ … │
│ Torgersen │          19.3 │               193 │        3450 │ female │ … │
└───────────┴───────────────┴───────────────────┴─────────────┴────────┴───┘

Drop with selectors, mix and match

>>> import ibis.selectors as s
>>> t.drop("species", s.startswith("bill_")).head()
┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━┓
┃ island    ┃ flipper_length_mm ┃ body_mass_g ┃ sex    ┃ year  ┃
┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━┩
│ string    │ int64             │ int64       │ string │ int64 │
├───────────┼───────────────────┼─────────────┼────────┼───────┤
│ Torgersen │               181 │        3750 │ male   │  2007 │
│ Torgersen │               186 │        3800 │ female │  2007 │
│ Torgersen │               195 │        3250 │ female │  2007 │
│ Torgersen │              NULL │        NULL │ NULL   │  2007 │
│ Torgersen │               193 │        3450 │ female │  2007 │
└───────────┴───────────────────┴─────────────┴────────┴───────┘
Source code in ibis/expr/types/relations.py
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
def drop(self, *fields: str | Selector) -> Table:
    """Remove fields from a table.

    Parameters
    ----------
    fields
        Fields to drop. Strings and selectors are accepted.

    Returns
    -------
    Table
        A table with all columns matching `fields` removed.

    Examples
    --------
    >>> import ibis
    >>> 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 │            nan │           nan │              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 │ … │
    │ …       │ …         │              … │             … │                 … │ … │
    └─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘

    Drop one or more columns

    >>> t.drop("species").head()
    ┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━┓
    ┃ island    ┃ bill_length_mm ┃ bill_depth_mm ┃ flipper_length_mm ┃ … ┃
    ┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━┩
    │ string    │ float64        │ float64       │ int64             │ … │
    ├───────────┼────────────────┼───────────────┼───────────────────┼───┤
    │ Torgersen │           39.1 │          18.7 │               181 │ … │
    │ Torgersen │           39.5 │          17.4 │               186 │ … │
    │ Torgersen │           40.3 │          18.0 │               195 │ … │
    │ Torgersen │            nan │           nan │              NULL │ … │
    │ Torgersen │           36.7 │          19.3 │               193 │ … │
    └───────────┴────────────────┴───────────────┴───────────────────┴───┘
    >>> t.drop("species", "bill_length_mm").head()
    ┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━┓
    ┃ island    ┃ bill_depth_mm ┃ flipper_length_mm ┃ body_mass_g ┃ sex    ┃ … ┃
    ┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━┩
    │ string    │ float64       │ int64             │ int64       │ string │ … │
    ├───────────┼───────────────┼───────────────────┼─────────────┼────────┼───┤
    │ Torgersen │          18.7 │               181 │        3750 │ male   │ … │
    │ Torgersen │          17.4 │               186 │        3800 │ female │ … │
    │ Torgersen │          18.0 │               195 │        3250 │ female │ … │
    │ Torgersen │           nan │              NULL │        NULL │ NULL   │ … │
    │ Torgersen │          19.3 │               193 │        3450 │ female │ … │
    └───────────┴───────────────┴───────────────────┴─────────────┴────────┴───┘

    Drop with selectors, mix and match

    >>> import ibis.selectors as s
    >>> t.drop("species", s.startswith("bill_")).head()
    ┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━┓
    ┃ island    ┃ flipper_length_mm ┃ body_mass_g ┃ sex    ┃ year  ┃
    ┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━┩
    │ string    │ int64             │ int64       │ string │ int64 │
    ├───────────┼───────────────────┼─────────────┼────────┼───────┤
    │ Torgersen │               181 │        3750 │ male   │  2007 │
    │ Torgersen │               186 │        3800 │ female │  2007 │
    │ Torgersen │               195 │        3250 │ female │  2007 │
    │ Torgersen │              NULL │        NULL │ NULL   │  2007 │
    │ Torgersen │               193 │        3450 │ female │  2007 │
    └───────────┴───────────────────┴─────────────┴────────┴───────┘
    """
    from ibis import selectors as s

    if not fields:
        # no-op if nothing to be dropped
        return self

    if missing_fields := {f for f in fields if isinstance(f, str)}.difference(
        self.schema().names
    ):
        raise KeyError(f"Fields not in table: {sorted(missing_fields)}")

    sels = (s.c(f) if isinstance(f, str) else f for f in fields)
    return self.select(~s.any_of(*sels))

dropna(subset=None, how='any')

Remove rows with null values from the table.

Parameters:

Name Type Description Default
subset Sequence[str] | str | None

Columns names to consider when dropping nulls. By default all columns are considered.

None
how Literal['any', 'all']

Determine whether a row is removed if there is at least one null value in the row ('any'), or if all row values are null ('all').

'any'

Returns:

Type Description
Table

Table expression

Examples:

>>> import ibis
>>> 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 │            nan │           nan │              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 │ … │
│ …       │ …         │              … │             … │                 … │ … │
└─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
>>> t.count()
344
>>> t.dropna(["bill_length_mm", "body_mass_g"]).count()
342
>>> t.dropna(how="all").count()  # no rows where all columns are null
344
Source code in ibis/expr/types/relations.py
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
def dropna(
    self,
    subset: Sequence[str] | str | None = None,
    how: Literal["any", "all"] = "any",
) -> Table:
    """Remove rows with null values from the table.

    Parameters
    ----------
    subset
        Columns names to consider when dropping nulls. By default all columns
        are considered.
    how
        Determine whether a row is removed if there is **at least one null
        value in the row** (`'any'`), or if **all** row values are null
        (`'all'`).

    Returns
    -------
    Table
        Table expression

    Examples
    --------
    >>> import ibis
    >>> 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 │            nan │           nan │              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 │ … │
    │ …       │ …         │              … │             … │                 … │ … │
    └─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
    >>> t.count()
    344
    >>> t.dropna(["bill_length_mm", "body_mass_g"]).count()
    342
    >>> t.dropna(how="all").count()  # no rows where all columns are null
    344
    """
    if subset is not None:
        subset = bind_expr(self, util.promote_list(subset))
    return ops.DropNa(self, how, subset).to_expr()

fillna(replacements)

Fill null values in a table expression.

There is potential lack of type stability with the fillna API

For example, different library versions may impact whether a given backend promotes integer replacement values to floats.

Parameters:

Name Type Description Default
replacements ir.Scalar | Mapping[str, ir.Scalar]

Value with which to fill nulls. If replacements is a mapping, the keys are column names that map to their replacement value. If passed as a scalar all columns are filled with that value.

required

Examples:

>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.examples.penguins.fetch()
>>> t.sex
┏━━━━━━━━┓
┃ sex    ┃
┡━━━━━━━━┩
│ string │
├────────┤
│ male   │
│ female │
│ female │
│ NULL   │
│ female │
│ male   │
│ female │
│ male   │
│ NULL   │
│ NULL   │
│ …      │
└────────┘
>>> t.fillna({"sex": "unrecorded"}).sex
┏━━━━━━━━━━━━┓
┃ sex        ┃
┡━━━━━━━━━━━━┩
│ string     │
├────────────┤
│ male       │
│ female     │
│ female     │
│ unrecorded │
│ female     │
│ male       │
│ female     │
│ male       │
│ unrecorded │
│ unrecorded │
│ …          │
└────────────┘

Returns:

Type Description
Table

Table expression

Source code in ibis/expr/types/relations.py
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
def fillna(
    self,
    replacements: ir.Scalar | Mapping[str, ir.Scalar],
) -> Table:
    """Fill null values in a table expression.

    !!! note "There is potential lack of type stability with the `fillna` API"

        For example, different library versions may impact whether a given
        backend promotes integer replacement values to floats.

    Parameters
    ----------
    replacements
        Value with which to fill nulls. If `replacements` is a mapping, the
        keys are column names that map to their replacement value. If
        passed as a scalar all columns are filled with that value.

    Examples
    --------
    >>> import ibis
    >>> ibis.options.interactive = True
    >>> t = ibis.examples.penguins.fetch()
    >>> t.sex
    ┏━━━━━━━━┓
    ┃ sex    ┃
    ┡━━━━━━━━┩
    │ string │
    ├────────┤
    │ male   │
    │ female │
    │ female │
    │ NULL   │
    │ female │
    │ male   │
    │ female │
    │ male   │
    │ NULL   │
    │ NULL   │
    │ …      │
    └────────┘
    >>> t.fillna({"sex": "unrecorded"}).sex
    ┏━━━━━━━━━━━━┓
    ┃ sex        ┃
    ┡━━━━━━━━━━━━┩
    │ string     │
    ├────────────┤
    │ male       │
    │ female     │
    │ female     │
    │ unrecorded │
    │ female     │
    │ male       │
    │ female     │
    │ male       │
    │ unrecorded │
    │ unrecorded │
    │ …          │
    └────────────┘

    Returns
    -------
    Table
        Table expression
    """
    schema = self.schema()

    if isinstance(replacements, collections.abc.Mapping):
        for col, val in replacements.items():
            if col not in schema:
                columns_formatted = ', '.join(map(repr, schema.names))
                raise com.IbisTypeError(
                    f"Column {col!r} is not found in table. "
                    f"Existing columns: {columns_formatted}."
                ) from None

            col_type = schema[col]
            val_type = val.type() if isinstance(val, Expr) else dt.infer(val)
            if not dt.castable(val_type, col_type):
                raise com.IbisTypeError(
                    f"Cannot fillna on column {col!r} of type {col_type} with a "
                    f"value of type {val_type}"
                )
    else:
        val_type = (
            replacements.type()
            if isinstance(replacements, Expr)
            else dt.infer(replacements)
        )
        for col, col_type in schema.items():
            if col_type.nullable and not dt.castable(val_type, col_type):
                raise com.IbisTypeError(
                    f"Cannot fillna on column {col!r} of type {col_type} with a "
                    f"value of type {val_type} - pass in an explicit mapping "
                    f"of fill values to `fillna` instead."
                )
    return ops.FillNa(self, replacements).to_expr()

filter(predicates)

Select rows from table based on predicates.

Parameters:

Name Type Description Default
predicates ir.BooleanValue | Sequence[ir.BooleanValue] | IfAnyAll

Boolean value expressions used to select rows in table.

required

Returns:

Type Description
Table

Filtered table expression

Examples:

>>> import ibis
>>> 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 │            nan │           nan │              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 │ … │
│ …       │ …         │              … │             … │                 … │ … │
└─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
>>> t.filter([t.species == "Adelie", t.body_mass_g > 3500]).sex.value_counts().dropna("sex")
┏━━━━━━━━┳━━━━━━━━━━━┓
┃ sex    ┃ sex_count ┃
┡━━━━━━━━╇━━━━━━━━━━━┩
│ string │ int64     │
├────────┼───────────┤
│ male   │        68 │
│ female │        22 │
└────────┴───────────┘
Source code in ibis/expr/types/relations.py
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
def filter(
    self,
    predicates: ir.BooleanValue | Sequence[ir.BooleanValue] | IfAnyAll,
) -> Table:
    """Select rows from `table` based on `predicates`.

    Parameters
    ----------
    predicates
        Boolean value expressions used to select rows in `table`.

    Returns
    -------
    Table
        Filtered table expression

    Examples
    --------
    >>> import ibis
    >>> 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 │            nan │           nan │              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 │ … │
    │ …       │ …         │              … │             … │                 … │ … │
    └─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
    >>> t.filter([t.species == "Adelie", t.body_mass_g > 3500]).sex.value_counts().dropna("sex")
    ┏━━━━━━━━┳━━━━━━━━━━━┓
    ┃ sex    ┃ sex_count ┃
    ┡━━━━━━━━╇━━━━━━━━━━━┩
    │ string │ int64     │
    ├────────┼───────────┤
    │ male   │        68 │
    │ female │        22 │
    └────────┴───────────┘
    """
    import ibis.expr.analysis as an

    resolved_predicates = _resolve_predicates(self, predicates)
    predicates = [
        an._rewrite_filter(pred.op() if isinstance(pred, Expr) else pred)
        for pred in resolved_predicates
    ]
    return an.apply_filter(self.op(), predicates).to_expr()

group_by(by=None, **key_exprs)

Create a grouped table expression.

Parameters:

Name Type Description Default
by str | ir.Value | Iterable[str] | Iterable[ir.Value] | None

Grouping expressions

None
key_exprs str | ir.Value | Iterable[str] | Iterable[ir.Value]

Named grouping expressions

{}

Returns:

Type Description
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())
┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━┓
┃ fruit  ┃ total_cost ┃ avg_cost ┃
┡━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━┩
│ string │ float64    │ float64  │
├────────┼────────────┼──────────┤
│ apple  │       1.00 │     0.50 │
│ banana │       0.25 │     0.25 │
│ orange │       0.33 │     0.33 │
└────────┴────────────┴──────────┘
Source code in ibis/expr/types/relations.py
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
def group_by(
    self,
    by: str | ir.Value | Iterable[str] | Iterable[ir.Value] | None = None,
    **key_exprs: str | ir.Value | Iterable[str] | Iterable[ir.Value],
) -> GroupedTable:
    """Create a grouped table expression.

    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())
    ┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━┓
    ┃ 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

    return GroupedTable(self, by, **key_exprs)

head(n=5)

Select the first n rows of a table.

The result set is not deterministic without a call to order_by.

Parameters:

Name Type Description Default
n int

Number of rows to include

5

Returns:

Type Description
Table

self limited to n rows

Examples:

>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.memtable({"a": [1, 1, 2], "b": ["c", "a", "a"]})
>>> t
┏━━━━━━━┳━━━━━━━━┓
┃ a     ┃ b      ┃
┡━━━━━━━╇━━━━━━━━┩
│ int64 │ string │
├───────┼────────┤
│     1 │ c      │
│     1 │ a      │
│     2 │ a      │
└───────┴────────┘
>>> t.head(2)
┏━━━━━━━┳━━━━━━━━┓
┃ a     ┃ b      ┃
┡━━━━━━━╇━━━━━━━━┩
│ int64 │ string │
├───────┼────────┤
│     1 │ c      │
│     1 │ a      │
└───────┴────────┘
See Also

Table.limit Table.order_by

Source code in ibis/expr/types/relations.py
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
def head(self, n: int = 5) -> Table:
    """Select the first `n` rows of a table.

    !!! note "The result set is not deterministic without a call to [`order_by`][ibis.expr.types.relations.Table.order_by]."

    Parameters
    ----------
    n
        Number of rows to include

    Returns
    -------
    Table
        `self` limited to `n` rows

    Examples
    --------
    >>> import ibis
    >>> ibis.options.interactive = True
    >>> t = ibis.memtable({"a": [1, 1, 2], "b": ["c", "a", "a"]})
    >>> t
    ┏━━━━━━━┳━━━━━━━━┓
    ┃ a     ┃ b      ┃
    ┡━━━━━━━╇━━━━━━━━┩
    │ int64 │ string │
    ├───────┼────────┤
    │     1 │ c      │
    │     1 │ a      │
    │     2 │ a      │
    └───────┴────────┘
    >>> t.head(2)
    ┏━━━━━━━┳━━━━━━━━┓
    ┃ a     ┃ b      ┃
    ┡━━━━━━━╇━━━━━━━━┩
    │ int64 │ string │
    ├───────┼────────┤
    │     1 │ c      │
    │     1 │ a      │
    └───────┴────────┘

    See Also
    --------
    [`Table.limit`][ibis.expr.types.relations.Table.limit]
    [`Table.order_by`][ibis.expr.types.relations.Table.order_by]
    """
    return self.limit(n=n)

info()

Return summary information about a table.

Returns:

Type Description
Table

Summary of self

Examples:

>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.examples.penguins.fetch()
>>> t.info()
┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━┳━━━┓
┃ name              ┃ type    ┃ nullable ┃ nulls ┃ non_nulls ┃ null_frac ┃ … ┃
┡━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━╇━━━┩
│ string            │ string  │ boolean  │ int64 │ int64     │ float64   │ … │
├───────────────────┼─────────┼──────────┼───────┼───────────┼───────────┼───┤
│ species           │ string  │ True     │     0 │       344 │  0.000000 │ … │
│ island            │ string  │ True     │     0 │       344 │  0.000000 │ … │
│ bill_length_mm    │ float64 │ True     │     2 │       342 │  0.005814 │ … │
│ bill_depth_mm     │ float64 │ True     │     2 │       342 │  0.005814 │ … │
│ flipper_length_mm │ int64   │ True     │     2 │       342 │  0.005814 │ … │
│ body_mass_g       │ int64   │ True     │     2 │       342 │  0.005814 │ … │
│ sex               │ string  │ True     │    11 │       333 │  0.031977 │ … │
│ year              │ int64   │ True     │     0 │       344 │  0.000000 │ … │
└───────────────────┴─────────┴──────────┴───────┴───────────┴───────────┴───┘
Source code in ibis/expr/types/relations.py
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
def info(self) -> Table:
    """Return summary information about a table.

    Returns
    -------
    Table
        Summary of `self`

    Examples
    --------
    >>> import ibis
    >>> ibis.options.interactive = True
    >>> t = ibis.examples.penguins.fetch()
    >>> t.info()
    ┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━┳━━━┓
    ┃ name              ┃ type    ┃ nullable ┃ nulls ┃ non_nulls ┃ null_frac ┃ … ┃
    ┡━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━╇━━━┩
    │ string            │ string  │ boolean  │ int64 │ int64     │ float64   │ … │
    ├───────────────────┼─────────┼──────────┼───────┼───────────┼───────────┼───┤
    │ species           │ string  │ True     │     0 │       344 │  0.000000 │ … │
    │ island            │ string  │ True     │     0 │       344 │  0.000000 │ … │
    │ bill_length_mm    │ float64 │ True     │     2 │       342 │  0.005814 │ … │
    │ bill_depth_mm     │ float64 │ True     │     2 │       342 │  0.005814 │ … │
    │ flipper_length_mm │ int64   │ True     │     2 │       342 │  0.005814 │ … │
    │ body_mass_g       │ int64   │ True     │     2 │       342 │  0.005814 │ … │
    │ sex               │ string  │ True     │    11 │       333 │  0.031977 │ … │
    │ year              │ int64   │ True     │     0 │       344 │  0.000000 │ … │
    └───────────────────┴─────────┴──────────┴───────┴───────────┴───────────┴───┘
    """
    from ibis import literal as lit

    aggs = []

    for pos, colname in enumerate(self.columns):
        col = self[colname]
        typ = col.type()
        agg = self.select(
            isna=ibis.case().when(col.isnull(), 1).else_(0).end()
        ).agg(
            name=lit(colname),
            type=lit(str(typ)),
            nullable=lit(int(typ.nullable)).cast("bool"),
            nulls=lambda t: t.isna.sum(),
            non_nulls=lambda t: (1 - t.isna).sum(),
            null_frac=lambda t: t.isna.mean(),
            pos=lit(pos),
        )
        aggs.append(agg)
    return ibis.union(*aggs).order_by(ibis.asc("pos"))

intersect(table, *rest, distinct=True)

Compute the set intersection of multiple table expressions.

The input tables must have identical schemas.

Parameters:

Name Type Description Default
table Table

A table expression

required
*rest Table

Additional table expressions

()
distinct bool

Only return distinct rows

True

Returns:

Type Description
Table

A new table containing the intersection of all input tables.

See Also

ibis.intersect

Examples:

>>> import ibis
>>> ibis.options.interactive = True
>>> t1 = ibis.memtable({"a": [1, 2]})
>>> t1
┏━━━━━━━┓
┃ a     ┃
┡━━━━━━━┩
│ int64 │
├───────┤
│     1 │
│     2 │
└───────┘
>>> t2 = ibis.memtable({"a": [2, 3]})
>>> t2
┏━━━━━━━┓
┃ a     ┃
┡━━━━━━━┩
│ int64 │
├───────┤
│     2 │
│     3 │
└───────┘
>>> t1.intersect(t2)
┏━━━━━━━┓
┃ a     ┃
┡━━━━━━━┩
│ int64 │
├───────┤
│     2 │
└───────┘
Source code in ibis/expr/types/relations.py
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
def intersect(self, table: Table, *rest: Table, distinct: bool = True) -> Table:
    """Compute the set intersection of multiple table expressions.

    The input tables must have identical schemas.

    Parameters
    ----------
    table
        A table expression
    *rest
        Additional table expressions
    distinct
        Only return distinct rows

    Returns
    -------
    Table
        A new table containing the intersection of all input tables.

    See Also
    --------
    [`ibis.intersect`][ibis.intersect]

    Examples
    --------
    >>> import ibis
    >>> ibis.options.interactive = True
    >>> t1 = ibis.memtable({"a": [1, 2]})
    >>> t1
    ┏━━━━━━━┓
    ┃ a     ┃
    ┡━━━━━━━┩
    │ int64 │
    ├───────┤
    │     1 │
    │     2 │
    └───────┘
    >>> t2 = ibis.memtable({"a": [2, 3]})
    >>> t2
    ┏━━━━━━━┓
    ┃ a     ┃
    ┡━━━━━━━┩
    │ int64 │
    ├───────┤
    │     2 │
    │     3 │
    └───────┘
    >>> t1.intersect(t2)
    ┏━━━━━━━┓
    ┃ a     ┃
    ┡━━━━━━━┩
    │ int64 │
    ├───────┤
    │     2 │
    └───────┘
    """
    node = ops.Intersection(self, table, distinct=distinct)
    for table in rest:
        node = ops.Intersection(node, table, distinct=distinct)
    return node.to_expr().select(self.columns)

join(left, right, predicates=(), how='inner', *, lname='', rname='{name}_right')

Perform a join between two tables.

Parameters:

Name Type Description Default
left Table

Left table to join

required
right Table

Right table to join

required
predicates str | Sequence[str | tuple[str | ir.Column, str | ir.Column] | ir.BooleanColumn]

Boolean or column names to join on

()
how Literal['inner', 'left', 'outer', 'right', 'semi', 'anti', 'any_inner', 'any_left', 'left_semi']

Join method

'inner'
lname str

A format string to use to rename overlapping columns in the left table (e.g. "left_{name}").

''
rname str

A format string to use to rename overlapping columns in the right table (e.g. "right_{name}").

'{name}_right'

Examples:

>>> import ibis
>>> import ibis.selectors as s
>>> import ibis.examples as ex
>>> from ibis import _
>>> ibis.options.interactive = True
>>> movies = ex.ml_latest_small_movies.fetch()
>>> movies
┏━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ movieId ┃ title                            ┃ genres                          ┃
┡━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ int64   │ string                           │ string                          │
├─────────┼──────────────────────────────────┼─────────────────────────────────┤
│       1 │ Toy Story (1995)                 │ Adventure|Animation|Children|C… │
│       2 │ Jumanji (1995)                   │ Adventure|Children|Fantasy      │
│       3 │ Grumpier Old Men (1995)          │ Comedy|Romance                  │
│       4 │ Waiting to Exhale (1995)         │ Comedy|Drama|Romance            │
│       5 │ Father of the Bride Part II (19… │ Comedy                          │
│       6 │ Heat (1995)                      │ Action|Crime|Thriller           │
│       7 │ Sabrina (1995)                   │ Comedy|Romance                  │
│       8 │ Tom and Huck (1995)              │ Adventure|Children              │
│       9 │ Sudden Death (1995)              │ Action                          │
│      10 │ GoldenEye (1995)                 │ Action|Adventure|Thriller       │
│       … │ …                                │ …                               │
└─────────┴──────────────────────────────────┴─────────────────────────────────┘
>>> links = ex.ml_latest_small_links.fetch()
>>> links
┏━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┓
┃ movieId ┃ imdbId  ┃ tmdbId ┃
┡━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━┩
│ int64   │ string  │ int64  │
├─────────┼─────────┼────────┤
│       1 │ 0114709 │    862 │
│       2 │ 0113497 │   8844 │
│       3 │ 0113228 │  15602 │
│       4 │ 0114885 │  31357 │
│       5 │ 0113041 │  11862 │
│       6 │ 0113277 │    949 │
│       7 │ 0114319 │  11860 │
│       8 │ 0112302 │  45325 │
│       9 │ 0114576 │   9091 │
│      10 │ 0113189 │    710 │
│       … │ …       │      … │
└─────────┴─────────┴────────┘

Implicit inner equality join on the shared movieId column

>>> linked = movies.join(links, "movieId", how="inner")
>>> linked.head()
┏━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┓
┃ movieId ┃ title                  ┃ genres                 ┃ imdbId  ┃ tmdbId ┃
┡━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━┩
│ int64   │ string                 │ string                 │ string  │ int64  │
├─────────┼────────────────────────┼────────────────────────┼─────────┼────────┤
│       1 │ Toy Story (1995)       │ Adventure|Animation|C… │ 0114709 │    862 │
│       2 │ Jumanji (1995)         │ Adventure|Children|Fa… │ 0113497 │   8844 │
│       3 │ Grumpier Old Men (199… │ Comedy|Romance         │ 0113228 │  15602 │
│       4 │ Waiting to Exhale (19… │ Comedy|Drama|Romance   │ 0114885 │  31357 │
│       5 │ Father of the Bride P… │ Comedy                 │ 0113041 │  11862 │
└─────────┴────────────────────────┴────────────────────────┴─────────┴────────┘

Explicit equality join using the default how value of "inner"

>>> linked = movies.join(links, movies.movieId == links.movieId)
>>> linked.head()
┏━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┓
┃ movieId ┃ title                  ┃ genres                 ┃ imdbId  ┃ tmdbId ┃
┡━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━┩
│ int64   │ string                 │ string                 │ string  │ int64  │
├─────────┼────────────────────────┼────────────────────────┼─────────┼────────┤
│       1 │ Toy Story (1995)       │ Adventure|Animation|C… │ 0114709 │    862 │
│       2 │ Jumanji (1995)         │ Adventure|Children|Fa… │ 0113497 │   8844 │
│       3 │ Grumpier Old Men (199… │ Comedy|Romance         │ 0113228 │  15602 │
│       4 │ Waiting to Exhale (19… │ Comedy|Drama|Romance   │ 0114885 │  31357 │
│       5 │ Father of the Bride P… │ Comedy                 │ 0113041 │  11862 │
└─────────┴────────────────────────┴────────────────────────┴─────────┴────────┘
Source code in ibis/expr/types/relations.py
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
def join(
    left: Table,
    right: Table,
    predicates: str
    | Sequence[
        str | tuple[str | ir.Column, str | ir.Column] | ir.BooleanColumn
    ] = (),
    how: Literal[
        'inner',
        'left',
        'outer',
        'right',
        'semi',
        'anti',
        'any_inner',
        'any_left',
        'left_semi',
    ] = 'inner',
    *,
    lname: str = "",
    rname: str = "{name}_right",
) -> Table:
    """Perform a join between two tables.

    Parameters
    ----------
    left
        Left table to join
    right
        Right table to join
    predicates
        Boolean or column names to join on
    how
        Join method
    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}"``).

    Examples
    --------
    >>> import ibis
    >>> import ibis.selectors as s
    >>> import ibis.examples as ex
    >>> from ibis import _
    >>> ibis.options.interactive = True
    >>> movies = ex.ml_latest_small_movies.fetch()
    >>> movies
    ┏━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
    ┃ movieId ┃ title                            ┃ genres                          ┃
    ┡━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
    │ int64   │ string                           │ string                          │
    ├─────────┼──────────────────────────────────┼─────────────────────────────────┤
    │       1 │ Toy Story (1995)                 │ Adventure|Animation|Children|C… │
    │       2 │ Jumanji (1995)                   │ Adventure|Children|Fantasy      │
    │       3 │ Grumpier Old Men (1995)          │ Comedy|Romance                  │
    │       4 │ Waiting to Exhale (1995)         │ Comedy|Drama|Romance            │
    │       5 │ Father of the Bride Part II (19… │ Comedy                          │
    │       6 │ Heat (1995)                      │ Action|Crime|Thriller           │
    │       7 │ Sabrina (1995)                   │ Comedy|Romance                  │
    │       8 │ Tom and Huck (1995)              │ Adventure|Children              │
    │       9 │ Sudden Death (1995)              │ Action                          │
    │      10 │ GoldenEye (1995)                 │ Action|Adventure|Thriller       │
    │       … │ …                                │ …                               │
    └─────────┴──────────────────────────────────┴─────────────────────────────────┘
    >>> links = ex.ml_latest_small_links.fetch()
    >>> links
    ┏━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┓
    ┃ movieId ┃ imdbId  ┃ tmdbId ┃
    ┡━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━┩
    │ int64   │ string  │ int64  │
    ├─────────┼─────────┼────────┤
    │       1 │ 0114709 │    862 │
    │       2 │ 0113497 │   8844 │
    │       3 │ 0113228 │  15602 │
    │       4 │ 0114885 │  31357 │
    │       5 │ 0113041 │  11862 │
    │       6 │ 0113277 │    949 │
    │       7 │ 0114319 │  11860 │
    │       8 │ 0112302 │  45325 │
    │       9 │ 0114576 │   9091 │
    │      10 │ 0113189 │    710 │
    │       … │ …       │      … │
    └─────────┴─────────┴────────┘

    Implicit inner equality join on the shared `movieId` column

    >>> linked = movies.join(links, "movieId", how="inner")
    >>> linked.head()
    ┏━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┓
    ┃ movieId ┃ title                  ┃ genres                 ┃ imdbId  ┃ tmdbId ┃
    ┡━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━┩
    │ int64   │ string                 │ string                 │ string  │ int64  │
    ├─────────┼────────────────────────┼────────────────────────┼─────────┼────────┤
    │       1 │ Toy Story (1995)       │ Adventure|Animation|C… │ 0114709 │    862 │
    │       2 │ Jumanji (1995)         │ Adventure|Children|Fa… │ 0113497 │   8844 │
    │       3 │ Grumpier Old Men (199… │ Comedy|Romance         │ 0113228 │  15602 │
    │       4 │ Waiting to Exhale (19… │ Comedy|Drama|Romance   │ 0114885 │  31357 │
    │       5 │ Father of the Bride P… │ Comedy                 │ 0113041 │  11862 │
    └─────────┴────────────────────────┴────────────────────────┴─────────┴────────┘

    Explicit equality join using the default `how` value of `"inner"`

    >>> linked = movies.join(links, movies.movieId == links.movieId)
    >>> linked.head()
    ┏━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┓
    ┃ movieId ┃ title                  ┃ genres                 ┃ imdbId  ┃ tmdbId ┃
    ┡━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━┩
    │ int64   │ string                 │ string                 │ string  │ int64  │
    ├─────────┼────────────────────────┼────────────────────────┼─────────┼────────┤
    │       1 │ Toy Story (1995)       │ Adventure|Animation|C… │ 0114709 │    862 │
    │       2 │ Jumanji (1995)         │ Adventure|Children|Fa… │ 0113497 │   8844 │
    │       3 │ Grumpier Old Men (199… │ Comedy|Romance         │ 0113228 │  15602 │
    │       4 │ Waiting to Exhale (19… │ Comedy|Drama|Romance   │ 0114885 │  31357 │
    │       5 │ Father of the Bride P… │ Comedy                 │ 0113041 │  11862 │
    └─────────┴────────────────────────┴────────────────────────┴─────────┴────────┘
    """

    _join_classes = {
        'inner': ops.InnerJoin,
        'left': ops.LeftJoin,
        'any_inner': ops.AnyInnerJoin,
        'any_left': ops.AnyLeftJoin,
        'outer': ops.OuterJoin,
        'right': ops.RightJoin,
        'left_semi': ops.LeftSemiJoin,
        'semi': ops.LeftSemiJoin,
        'anti': ops.LeftAntiJoin,
        'cross': ops.CrossJoin,
    }

    klass = _join_classes[how.lower()]
    expr = klass(left, right, predicates).to_expr()

    # semi/anti join only give access to the left table's fields, so
    # there's never overlap
    if how in ("left_semi", "semi", "anti"):
        return expr

    return ops.relations._dedup_join_columns(expr, lname=lname, rname=rname)

limit(n, offset=0)

Select n rows from self starting at offset.

The result set is not deterministic without a call to order_by.

Parameters:

Name Type Description Default
n int

Number of rows to include

required
offset int

Number of rows to skip first

0

Returns:

Type Description
Table

The first n rows of self starting at offset

Examples:

>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.memtable({"a": [1, 1, 2], "b": ["c", "a", "a"]})
>>> t
┏━━━━━━━┳━━━━━━━━┓
┃ a     ┃ b      ┃
┡━━━━━━━╇━━━━━━━━┩
│ int64 │ string │
├───────┼────────┤
│     1 │ c      │
│     1 │ a      │
│     2 │ a      │
└───────┴────────┘
>>> t.limit(2)
┏━━━━━━━┳━━━━━━━━┓
┃ a     ┃ b      ┃
┡━━━━━━━╇━━━━━━━━┩
│ int64 │ string │
├───────┼────────┤
│     1 │ c      │
│     1 │ a      │
└───────┴────────┘
See Also

Table.order_by

Source code in ibis/expr/types/relations.py
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
def limit(self, n: int, offset: int = 0) -> Table:
    """Select `n` rows from `self` starting at `offset`.

    !!! note "The result set is not deterministic without a call to [`order_by`][ibis.expr.types.relations.Table.order_by]."

    Parameters
    ----------
    n
        Number of rows to include
    offset
        Number of rows to skip first

    Returns
    -------
    Table
        The first `n` rows of `self` starting at `offset`

    Examples
    --------
    >>> import ibis
    >>> ibis.options.interactive = True
    >>> t = ibis.memtable({"a": [1, 1, 2], "b": ["c", "a", "a"]})
    >>> t
    ┏━━━━━━━┳━━━━━━━━┓
    ┃ a     ┃ b      ┃
    ┡━━━━━━━╇━━━━━━━━┩
    │ int64 │ string │
    ├───────┼────────┤
    │     1 │ c      │
    │     1 │ a      │
    │     2 │ a      │
    └───────┴────────┘
    >>> t.limit(2)
    ┏━━━━━━━┳━━━━━━━━┓
    ┃ a     ┃ b      ┃
    ┡━━━━━━━╇━━━━━━━━┩
    │ int64 │ string │
    ├───────┼────────┤
    │     1 │ c      │
    │     1 │ a      │
    └───────┴────────┘

    See Also
    --------
    [`Table.order_by`][ibis.expr.types.relations.Table.order_by]
    """
    return ops.Limit(self, n, offset=offset).to_expr()

mutate(exprs=None, **mutations)

Add columns to a table expression.

Parameters:

Name Type Description Default
exprs Sequence[ir.Expr] | None

List of named expressions to add as columns

None
mutations ir.Value

Named expressions using keyword arguments

{}

Returns:

Type Description
Table

Table expression with additional columns

Examples:

>>> import ibis
>>> import ibis.selectors as s
>>> from ibis import _
>>> ibis.options.interactive = True
>>> t = ibis.examples.penguins.fetch().select("species", "year", "bill_length_mm")
>>> t
┏━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━━━━━┓
┃ species ┃ year  ┃ bill_length_mm ┃
┡━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━━━━━┩
│ string  │ int64 │ float64        │
├─────────┼───────┼────────────────┤
│ Adelie  │  2007 │           39.1 │
│ Adelie  │  2007 │           39.5 │
│ Adelie  │  2007 │           40.3 │
│ Adelie  │  2007 │            nan │
│ Adelie  │  2007 │           36.7 │
│ Adelie  │  2007 │           39.3 │
│ Adelie  │  2007 │           38.9 │
│ Adelie  │  2007 │           39.2 │
│ Adelie  │  2007 │           34.1 │
│ Adelie  │  2007 │           42.0 │
│ …       │     … │              … │
└─────────┴───────┴────────────────┘

Add a new column from a per-element expression

>>> t.mutate(next_year=_.year + 1).head()
┏━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━┓
┃ species ┃ year  ┃ bill_length_mm ┃ next_year ┃
┡━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━┩
│ string  │ int64 │ float64        │ int64     │
├─────────┼───────┼────────────────┼───────────┤
│ Adelie  │  2007 │           39.1 │      2008 │
│ Adelie  │  2007 │           39.5 │      2008 │
│ Adelie  │  2007 │           40.3 │      2008 │
│ Adelie  │  2007 │            nan │      2008 │
│ Adelie  │  2007 │           36.7 │      2008 │
└─────────┴───────┴────────────────┴───────────┘

Add a new column based on an aggregation. Note the automatic broadcasting.

>>> t.select("species", bill_demean=_.bill_length_mm - _.bill_length_mm.mean()).head()
┏━━━━━━━━━┳━━━━━━━━━━━━━┓
┃ species ┃ bill_demean ┃
┡━━━━━━━━━╇━━━━━━━━━━━━━┩
│ string  │ float64     │
├─────────┼─────────────┤
│ Adelie  │    -4.82193 │
│ Adelie  │    -4.42193 │
│ Adelie  │    -3.62193 │
│ Adelie  │         nan │
│ Adelie  │    -7.22193 │
└─────────┴─────────────┘

Mutate across multiple columns

>>> t.mutate(s.across(s.numeric() & ~s.c("year"), _ - _.mean())).head()
┏━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━━━━━┓
┃ species ┃ year  ┃ bill_length_mm ┃
┡━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━━━━━┩
│ string  │ int64 │ float64        │
├─────────┼───────┼────────────────┤
│ Adelie  │  2007 │       -4.82193 │
│ Adelie  │  2007 │       -4.42193 │
│ Adelie  │  2007 │       -3.62193 │
│ Adelie  │  2007 │            nan │
│ Adelie  │  2007 │       -7.22193 │
└─────────┴───────┴────────────────┘
Source code in ibis/expr/types/relations.py
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
def mutate(
    self, exprs: Sequence[ir.Expr] | None = None, **mutations: ir.Value
) -> Table:
    """Add columns to a table expression.

    Parameters
    ----------
    exprs
        List of named expressions to add as columns
    mutations
        Named expressions using keyword arguments

    Returns
    -------
    Table
        Table expression with additional columns

    Examples
    --------
    >>> import ibis
    >>> import ibis.selectors as s
    >>> from ibis import _
    >>> ibis.options.interactive = True
    >>> t = ibis.examples.penguins.fetch().select("species", "year", "bill_length_mm")
    >>> t
    ┏━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━━━━━┓
    ┃ species ┃ year  ┃ bill_length_mm ┃
    ┡━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━━━━━┩
    │ string  │ int64 │ float64        │
    ├─────────┼───────┼────────────────┤
    │ Adelie  │  2007 │           39.1 │
    │ Adelie  │  2007 │           39.5 │
    │ Adelie  │  2007 │           40.3 │
    │ Adelie  │  2007 │            nan │
    │ Adelie  │  2007 │           36.7 │
    │ Adelie  │  2007 │           39.3 │
    │ Adelie  │  2007 │           38.9 │
    │ Adelie  │  2007 │           39.2 │
    │ Adelie  │  2007 │           34.1 │
    │ Adelie  │  2007 │           42.0 │
    │ …       │     … │              … │
    └─────────┴───────┴────────────────┘

    Add a new column from a per-element expression

    >>> t.mutate(next_year=_.year + 1).head()
    ┏━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━┓
    ┃ species ┃ year  ┃ bill_length_mm ┃ next_year ┃
    ┡━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━┩
    │ string  │ int64 │ float64        │ int64     │
    ├─────────┼───────┼────────────────┼───────────┤
    │ Adelie  │  2007 │           39.1 │      2008 │
    │ Adelie  │  2007 │           39.5 │      2008 │
    │ Adelie  │  2007 │           40.3 │      2008 │
    │ Adelie  │  2007 │            nan │      2008 │
    │ Adelie  │  2007 │           36.7 │      2008 │
    └─────────┴───────┴────────────────┴───────────┘

    Add a new column based on an aggregation. Note the automatic broadcasting.

    >>> t.select("species", bill_demean=_.bill_length_mm - _.bill_length_mm.mean()).head()
    ┏━━━━━━━━━┳━━━━━━━━━━━━━┓
    ┃ species ┃ bill_demean ┃
    ┡━━━━━━━━━╇━━━━━━━━━━━━━┩
    │ string  │ float64     │
    ├─────────┼─────────────┤
    │ Adelie  │    -4.82193 │
    │ Adelie  │    -4.42193 │
    │ Adelie  │    -3.62193 │
    │ Adelie  │         nan │
    │ Adelie  │    -7.22193 │
    └─────────┴─────────────┘

    Mutate across multiple columns

    >>> t.mutate(s.across(s.numeric() & ~s.c("year"), _ - _.mean())).head()
    ┏━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━━━━━┓
    ┃ species ┃ year  ┃ bill_length_mm ┃
    ┡━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━━━━━┩
    │ string  │ int64 │ float64        │
    ├─────────┼───────┼────────────────┤
    │ Adelie  │  2007 │       -4.82193 │
    │ Adelie  │  2007 │       -4.42193 │
    │ Adelie  │  2007 │       -3.62193 │
    │ Adelie  │  2007 │            nan │
    │ Adelie  │  2007 │       -7.22193 │
    └─────────┴───────┴────────────────┘
    """
    import ibis.expr.analysis as an

    exprs = [] if exprs is None else util.promote_list(exprs)
    exprs = itertools.chain(
        itertools.chain.from_iterable(
            util.promote_list(_ensure_expr(self, expr)) for expr in exprs
        ),
        (
            e.name(name)
            for name, expr in mutations.items()
            for e in util.promote_list(_ensure_expr(self, expr))
        ),
    )
    mutation_exprs = an.get_mutation_exprs(list(exprs), self)
    return self.select(mutation_exprs)

nunique(where=None)

Compute the number of unique rows in the table.

Parameters:

Name Type Description Default
where ir.BooleanValue | None

Optional boolean expression to filter rows when counting.

None

Returns:

Type Description
IntegerScalar

Number of unique rows in the table

Examples:

>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.memtable({"a": ["foo", "bar", "bar"]})
>>> t
┏━━━━━━━━┓
┃ a      ┃
┡━━━━━━━━┩
│ string │
├────────┤
│ foo    │
│ bar    │
│ bar    │
└────────┘
>>> t.nunique()
2
>>> t.nunique(t.a != "foo")
1
Source code in ibis/expr/types/relations.py
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
def nunique(self, where: ir.BooleanValue | None = None) -> ir.IntegerScalar:
    """Compute the number of unique rows in the table.

    Parameters
    ----------
    where
        Optional boolean expression to filter rows when counting.

    Returns
    -------
    IntegerScalar
        Number of unique rows in the table

    Examples
    --------
    >>> import ibis
    >>> ibis.options.interactive = True
    >>> t = ibis.memtable({"a": ["foo", "bar", "bar"]})
    >>> t
    ┏━━━━━━━━┓
    ┃ a      ┃
    ┡━━━━━━━━┩
    │ string │
    ├────────┤
    │ foo    │
    │ bar    │
    │ bar    │
    └────────┘
    >>> t.nunique()
    2
    >>> t.nunique(t.a != "foo")
    1
    """
    return ops.CountDistinctStar(self, where=where).to_expr()

order_by(by)

Sort a table by one or more expressions.

Parameters:

Name Type Description Default
by str | ir.Column | tuple[str | ir.Column, bool] | Sequence[str] | Sequence[ir.Column] | Sequence[tuple[str | ir.Column, bool]] | None

Expressions to sort the table by.

required

Returns:

Type Description
Table

Sorted table

Examples:

>>> import ibis
>>> ibis.options.interactive = True
>>> t = ibis.memtable({"a": [1, 2, 3], "b": ["c", "b", "a"], "c": [4, 6, 5]})
>>> t
┏━━━━━━━┳━━━━━━━━┳━━━━━━━┓
┃ a     ┃ b      ┃ c     ┃
┡━━━━━━━╇━━━━━━━━╇━━━━━━━┩
│ int64 │ string │ int64 │
├───────┼────────┼───────┤
│     1 │ c      │     4 │
│     2 │ b      │     6 │
│     3 │ a      │     5 │
└───────┴────────┴───────┘
>>> t.order_by("b")
┏━━━━━━━┳━━━━━━━━┳━━━━━━━┓
┃ a     ┃ b      ┃ c     ┃
┡━━━━━━━╇━━━━━━━━╇━━━━━━━┩
│ int64 │ string │ int64 │
├───────┼────────┼───────┤
│     3 │ a      │     5 │
│     2 │ b      │     6 │
│     1 │ c      │     4 │
└───────┴────────┴───────┘
>>> t.order_by(ibis.desc("c"))
┏━━━━━━━┳━━━━━━━━┳━━━━━━━┓
┃ a     ┃ b      ┃ c     ┃
┡━━━━━━━╇━━━━━━━━╇━━━━━━━┩
│ int64 │ string │ int64 │
├───────┼────────┼───────┤
│     2 │ b      │     6 │
│     3 │ a      │     5 │
│     1 │ c      │     4 │
└───────┴────────┴───────┘
Source code in ibis/expr/types/relations.py
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
def order_by(
    self,
    by: str
    | ir.Column
    | tuple[str | ir.Column, bool]
    | Sequence[str]
    | Sequence[ir.Column]
    | Sequence[tuple[str | ir.Column, bool]]
    | None,
) -> Table:
    """Sort a table by one or more expressions.

    Parameters
    ----------
    by
        Expressions to sort the table by.

    Returns
    -------
    Table
        Sorted table

    Examples
    --------
    >>> import ibis
    >>> ibis.options.interactive = True
    >>> t = ibis.memtable({"a": [1, 2, 3], "b": ["c", "b", "a"], "c": [4, 6, 5]})
    >>> t
    ┏━━━━━━━┳━━━━━━━━┳━━━━━━━┓
    ┃ a     ┃ b      ┃ c     ┃
    ┡━━━━━━━╇━━━━━━━━╇━━━━━━━┩
    │ int64 │ string │ int64 │
    ├───────┼────────┼───────┤
    │     1 │ c      │     4 │
    │     2 │ b      │     6 │
    │     3 │ a      │     5 │
    └───────┴────────┴───────┘
    >>> t.order_by("b")
    ┏━━━━━━━┳━━━━━━━━┳━━━━━━━┓
    ┃ a     ┃ b      ┃ c     ┃
    ┡━━━━━━━╇━━━━━━━━╇━━━━━━━┩
    │ int64 │ string │ int64 │
    ├───────┼────────┼───────┤
    │     3 │ a      │     5 │
    │     2 │ b      │     6 │
    │     1 │ c      │     4 │
    └───────┴────────┴───────┘
    >>> t.order_by(ibis.desc("c"))
    ┏━━━━━━━┳━━━━━━━━┳━━━━━━━┓
    ┃ a     ┃ b      ┃ c     ┃
    ┡━━━━━━━╇━━━━━━━━╇━━━━━━━┩
    │ int64 │ string │ int64 │
    ├───────┼────────┼───────┤
    │     2 │ b      │     6 │
    │     3 │ a      │     5 │
    │     1 │ c      │     4 │
    └───────┴────────┴───────┘
    """
    used_tuple_syntax = False
    if isinstance(by, tuple):
        by = [by]
        used_tuple_syntax = True

    sort_keys = []
    for item in util.promote_list(by):
        if isinstance(item, tuple):
            if len(item) != 2:
                raise ValueError(
                    "Tuple must be of length 2, got {}".format(len(item))
                )
            item = (bind_expr(self, item[0]), item[1])
            used_tuple_syntax = True
        else:
            item = bind_expr(self, item)
        sort_keys.append(item)

    if used_tuple_syntax:
        util.warn_deprecated(
            "table.order_by((key, True)) and table.order_by((key, False)) syntax",
            as_of="6.0",
            removed_in="7.0",
            instead="Use ibis.desc(key) or ibis.asc(key) instead",
        )

    return self.op().order_by(sort_keys).to_expr()

pivot_longer(col, *, names_to='name', names_pattern='(.+)', names_transform=None, values_to='value', values_transform=None)

Transform a table from wider to longer.

Parameters:

Name Type Description Default
col str | s.Selector

String column name or selector.

required
names_to str | Iterable[str]

A string or iterable of strings indicating how to name the new pivoted columns.

'name'
names_pattern str | re.Pattern

Pattern to use to extract column names from the input. By default the entire column name is extracted.

'(.+)'
names_transform Callable[[str], ir.Value] | Mapping[str, Callable[[str], ir.Value]] | None

Function or mapping of a name in names_to to a function to transform a column name to a value.

None
values_to str

Name of the pivoted value column.

'value'
values_transform Callable[[ir.Value], ir.Value] | Deferred | None

Apply a function to the value column. This can be a lambda or deferred expression.

None

Returns:

Type Description
Table

Pivoted table

Examples:

Basic usage

>>> import ibis
>>> import ibis.selectors as s
>>> from ibis import _
>>> ibis.options.interactive = True
>>> relig_income = ibis.examples.relig_income_raw.fetch()
>>> relig_income
┏━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━┓
┃ religion                ┃ <$10k ┃ $10-20k ┃ $20-30k ┃ $30-40k ┃ $40-50k ┃ … ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━┩
│ string                  │ int64 │ int64   │ int64   │ int64   │ int64   │ … │
├─────────────────────────┼───────┼─────────┼─────────┼─────────┼─────────┼───┤
│ Agnostic                │    27 │      34 │      60 │      81 │      76 │ … │
│ Atheist                 │    12 │      27 │      37 │      52 │      35 │ … │
│ Buddhist                │    27 │      21 │      30 │      34 │      33 │ … │
│ Catholic                │   418 │     617 │     732 │     670 │     638 │ … │
│ Don’t know/refused      │    15 │      14 │      15 │      11 │      10 │ … │
│ Evangelical Prot        │   575 │     869 │    1064 │     982 │     881 │ … │
│ Hindu                   │     1 │       9 │       7 │       9 │      11 │ … │
│ Historically Black Prot │   228 │     244 │     236 │     238 │     197 │ … │
│ Jehovah's Witness       │    20 │      27 │      24 │      24 │      21 │ … │
│ Jewish                  │    19 │      19 │      25 │      25 │      30 │ … │
│ …                       │     … │       … │       … │       … │       … │ … │
└─────────────────────────┴───────┴─────────┴─────────┴─────────┴─────────┴───┘

Here we convert column names not matching the selector for the religion column and convert those names into values

>>> relig_income.pivot_longer(~s.c("religion"), names_to="income", values_to="count")
┏━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┓
┃ religion ┃ income             ┃ count ┃
┡━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━╇━━━━━━━┩
│ string   │ string             │ int64 │
├──────────┼────────────────────┼───────┤
│ Agnostic │ <$10k              │    27 │
│ Agnostic │ $10-20k            │    34 │
│ Agnostic │ $20-30k            │    60 │
│ Agnostic │ $30-40k            │    81 │
│ Agnostic │ $40-50k            │    76 │
│ Agnostic │ $50-75k            │   137 │
│ Agnostic │ $75-100k           │   122 │
│ Agnostic │ $100-150k          │   109 │
│ Agnostic │ >150k              │    84 │
│ Agnostic │ Don't know/refused │    96 │
│ …        │ …                  │     … │
└──────────┴────────────────────┴───────┘

Similarly for a different example dataset, we convert names to values but using a different selector and the default values_to value.

>>> world_bank_pop = ibis.examples.world_bank_pop_raw.fetch()
>>> world_bank_pop.head()
┏━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━┓
┃ country ┃ indicator   ┃ 2000         ┃ 2001         ┃ 2002         ┃ … ┃
┡━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━┩
│ string  │ string      │ float64      │ float64      │ float64      │ … │
├─────────┼─────────────┼──────────────┼──────────────┼──────────────┼───┤
│ ABW     │ SP.URB.TOTL │ 4.244400e+04 │ 4.304800e+04 │ 4.367000e+04 │ … │
│ ABW     │ SP.URB.GROW │ 1.182632e+00 │ 1.413021e+00 │ 1.434560e+00 │ … │
│ ABW     │ SP.POP.TOTL │ 9.085300e+04 │ 9.289800e+04 │ 9.499200e+04 │ … │
│ ABW     │ SP.POP.GROW │ 2.055027e+00 │ 2.225930e+00 │ 2.229056e+00 │ … │
│ AFG     │ SP.URB.TOTL │ 4.436299e+06 │ 4.648055e+06 │ 4.892951e+06 │ … │
└─────────┴─────────────┴──────────────┴──────────────┴──────────────┴───┘
>>> world_bank_pop.pivot_longer(s.matches(r"\d{4}"), names_to="year").head()
┏━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━┓
┃ country ┃ indicator   ┃ year   ┃ value   ┃
┡━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━┩
│ string  │ string      │ string │ float64 │
├─────────┼─────────────┼────────┼─────────┤
│ ABW     │ SP.URB.TOTL │ 2000   │ 42444.0 │
│ ABW     │ SP.URB.TOTL │ 2001   │ 43048.0 │
│ ABW     │ SP.URB.TOTL │ 2002   │ 43670.0 │
│ ABW     │ SP.URB.TOTL │ 2003   │ 44246.0 │
│ ABW     │ SP.URB.TOTL │ 2004   │ 44669.0 │
└─────────┴─────────────┴────────┴─────────┘

pivot_longer has some preprocessing capabiltiies like stripping a prefix and applying a function to column names

>>> billboard = ibis.examples.billboard.fetch()
>>> billboard
┏━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━┓
┃ artist         ┃ track                   ┃ date_entered ┃ wk1   ┃ wk2   ┃ … ┃
┡━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━┩
│ string         │ string                  │ date         │ int64 │ int64 │ … │
├────────────────┼─────────────────────────┼──────────────┼───────┼───────┼───┤
│ 2 Pac          │ Baby Don't Cry (Keep... │ 2000-02-26   │    87 │    82 │ … │
│ 2Ge+her        │ The Hardest Part Of ... │ 2000-09-02   │    91 │    87 │ … │
│ 3 Doors Down   │ Kryptonite              │ 2000-04-08   │    81 │    70 │ … │
│ 3 Doors Down   │ Loser                   │ 2000-10-21   │    76 │    76 │ … │
│ 504 Boyz       │ Wobble Wobble           │ 2000-04-15   │    57 │    34 │ … │
│ 98^0           │ Give Me Just One Nig... │ 2000-08-19   │    51 │    39 │ … │
│ A*Teens        │ Dancing Queen           │ 2000-07-08   │    97 │    97 │ … │
│ Aaliyah        │ I Don't Wanna           │ 2000-01-29   │    84 │    62 │ … │
│ Aaliyah        │ Try Again               │ 2000-03-18   │    59 │    53 │ … │
│ Adams, Yolanda │ Open My Heart           │ 2000-08-26   │    76 │    76 │ … │
│ …              │ …                       │ …            │     … │     … │ … │
└────────────────┴─────────────────────────┴──────────────┴───────┴───────┴───┘
>>> billboard.pivot_longer(
...     s.startswith("wk"),
...     names_to="week",
...     names_pattern=r"wk(.+)",
...     names_transform=int,
...     values_to="rank",
...     values_transform=_.cast("int"),
... ).dropna("rank")
┏━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━┓
┃ artist  ┃ track                   ┃ date_entered ┃ week ┃ rank  ┃
┡━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━┩
│ string  │ string                  │ date         │ int8 │ int64 │
├─────────┼─────────────────────────┼──────────────┼──────┼───────┤
│ 2 Pac   │ Baby Don't Cry (Keep... │ 2000-02-26   │    1 │    87 │
│ 2 Pac   │ Baby Don't Cry (Keep... │ 2000-02-26   │    2 │    82 │
│ 2 Pac   │ Baby Don't Cry (Keep... │ 2000-02-26   │    3 │    72 │
│ 2 Pac   │ Baby Don't Cry (Keep... │ 2000-02-26   │    4 │    77 │
│ 2 Pac   │ Baby Don't Cry (Keep... │ 2000-02-26   │    5 │    87 │
│ 2 Pac   │ Baby Don't Cry (Keep... │ 2000-02-26   │    6 │    94 │
│ 2 Pac   │ Baby Don't Cry (Keep... │ 2000-02-26   │    7 │    99 │
│ 2Ge+her │ The Hardest Part Of ... │ 2000-09-02   │    1 │    91 │
│ 2Ge+her │ The Hardest Part Of ... │ 2000-09-02   │    2 │    87 │
│ 2Ge+her │ The Hardest Part Of ... │ 2000-09-02   │    3 │    92 │
│ …       │ …                       │ …            │    … │     … │
└─────────┴─────────────────────────┴──────────────┴──────┴───────┘

You can use regular expression capture groups to extract multiple variables stored in column names

>>> who = ibis.examples.who.fetch()
>>> who
┏━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━┓
┃ country     ┃ iso2   ┃ iso3   ┃ year  ┃ new_sp_m014 ┃ new_sp_m1524 ┃ … ┃
┡━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━┩
│ string      │ string │ string │ int64 │ int64       │ int64        │ … │
├─────────────┼────────┼────────┼───────┼─────────────┼──────────────┼───┤
│ Afghanistan │ AF     │ AFG    │  1980 │        NULL │         NULL │ … │
│ Afghanistan │ AF     │ AFG    │  1981 │        NULL │         NULL │ … │
│ Afghanistan │ AF     │ AFG    │  1982 │        NULL │         NULL │ … │
│ Afghanistan │ AF     │ AFG    │  1983 │        NULL │         NULL │ … │
│ Afghanistan │ AF     │ AFG    │  1984 │        NULL │         NULL │ … │
│ Afghanistan │ AF     │ AFG    │  1985 │        NULL │         NULL │ … │
│ Afghanistan │ AF     │ AFG    │  1986 │        NULL │         NULL │ … │
│ Afghanistan │ AF     │ AFG    │  1987 │        NULL │         NULL │ … │
│ Afghanistan │ AF     │ AFG    │  1988 │        NULL │         NULL │ … │
│ Afghanistan │ AF     │ AFG    │  1989 │        NULL │         NULL │ … │
│ …           │ …      │ …      │     … │           … │            … │ … │
└─────────────┴────────┴────────┴───────┴─────────────┴──────────────┴───┘
>>> len(who.columns)
60
>>> who.pivot_longer(
...     s.r["new_sp_m014":"newrel_f65"],
...     names_to=["diagnosis", "gender", "age"],
...     names_pattern="new_?(.*)_(.)(.*)",
...     values_to="count",
... )
┏━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━┓
┃ country     ┃ iso2   ┃ iso3   ┃ year  ┃ diagnosis ┃ gender ┃ age    ┃ count ┃
┡━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━┩
│ string      │ string │ string │ int64 │ string    │ string │ string │ int64 │
├─────────────┼────────┼────────┼───────┼───────────┼────────┼────────┼───────┤
│ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ m      │ 014    │  NULL │
│ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ m      │ 1524   │  NULL │
│ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ m      │ 2534   │  NULL │
│ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ m      │ 3544   │  NULL │
│ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ m      │ 4554   │  NULL │
│ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ m      │ 5564   │  NULL │
│ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ m      │ 65     │  NULL │
│ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ f      │ 014    │  NULL │
│ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ f      │ 1524   │  NULL │
│ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ f      │ 2534   │  NULL │
│ …           │ …      │ …      │     … │ …         │ …      │ …      │     … │
└─────────────┴────────┴────────┴───────┴───────────┴────────┴────────┴───────┘

names_transform is flexible, and can be:

1. A mapping of one or more names in `names_to` to callable
2. A callable that will be applied to every name

Let's recode gender and age to numeric values using a mapping

>>> who.pivot_longer(
...     s.r["new_sp_m014":"newrel_f65"],
...     names_to=["diagnosis", "gender", "age"],
...     names_pattern="new_?(.*)_(.)(.*)",
...     names_transform=dict(
...         gender={"m": 1, "f": 2}.get,
...         age=dict(zip(["014", "1524", "2534", "3544", "4554", "5564", "65"], range(7))).get,
...     ),
...     values_to="count",
... )
┏━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━┳━━━━━━┳━━━━━━━┓
┃ country     ┃ iso2   ┃ iso3   ┃ year  ┃ diagnosis ┃ gender ┃ age  ┃ count ┃
┡━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━╇━━━━━━╇━━━━━━━┩
│ string      │ string │ string │ int64 │ string    │ int8   │ int8 │ int64 │
├─────────────┼────────┼────────┼───────┼───────────┼────────┼──────┼───────┤
│ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      1 │    0 │  NULL │
│ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      1 │    1 │  NULL │
│ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      1 │    2 │  NULL │
│ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      1 │    3 │  NULL │
│ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      1 │    4 │  NULL │
│ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      1 │    5 │  NULL │
│ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      1 │    6 │  NULL │
│ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      2 │    0 │  NULL │
│ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      2 │    1 │  NULL │
│ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      2 │    2 │  NULL │
│ …           │ …      │ …      │     … │ …         │      … │    … │     … │
└─────────────┴────────┴────────┴───────┴───────────┴────────┴──────┴───────┘

The number of match groups in names_pattern must match the length of names_to

>>> who.pivot_longer(
...     s.r["new_sp_m014":"newrel_f65"],
...     names_to=["diagnosis", "gender", "age"],
...     names_pattern="new_?(.*)_.(.*)",
... )
Traceback (most recent call last):
  ...
ibis.common.exceptions.IbisInputError: Number of match groups in `names_pattern` ...

names_transform must be a mapping or callable

>>> who.pivot_longer(s.r["new_sp_m014":"newrel_f65"], names_transform="upper")
Traceback (most recent call last):
  ...
ibis.common.exceptions.IbisTypeError: ... Got <class 'str'>
Source code in ibis/expr/types/relations.py
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
def pivot_longer(
    self,
    col: str | s.Selector,
    *,
    names_to: str | Iterable[str] = "name",
    names_pattern: str | re.Pattern = r"(.+)",
    names_transform: Callable[[str], ir.Value]
    | Mapping[str, Callable[[str], ir.Value]]
    | None = None,
    values_to: str = "value",
    values_transform: Callable[[ir.Value], ir.Value] | Deferred | None = None,
) -> Table:
    """Transform a table from wider to longer.

    Parameters
    ----------
    col
        String column name or selector.
    names_to
        A string or iterable of strings indicating how to name the new
        pivoted columns.
    names_pattern
        Pattern to use to extract column names from the input. By default
        the entire column name is extracted.
    names_transform
        Function or mapping of a name in `names_to` to a function to
        transform a column name to a value.
    values_to
        Name of the pivoted value column.
    values_transform
        Apply a function to the value column. This can be a lambda or
        deferred expression.

    Returns
    -------
    Table
        Pivoted table

    Examples
    --------
    Basic usage

    >>> import ibis
    >>> import ibis.selectors as s
    >>> from ibis import _
    >>> ibis.options.interactive = True
    >>> relig_income = ibis.examples.relig_income_raw.fetch()
    >>> relig_income
    ┏━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━┓
    ┃ religion                ┃ <$10k ┃ $10-20k ┃ $20-30k ┃ $30-40k ┃ $40-50k ┃ … ┃
    ┡━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━┩
    │ string                  │ int64 │ int64   │ int64   │ int64   │ int64   │ … │
    ├─────────────────────────┼───────┼─────────┼─────────┼─────────┼─────────┼───┤
    │ Agnostic                │    27 │      34 │      60 │      81 │      76 │ … │
    │ Atheist                 │    12 │      27 │      37 │      52 │      35 │ … │
    │ Buddhist                │    27 │      21 │      30 │      34 │      33 │ … │
    │ Catholic                │   418 │     617 │     732 │     670 │     638 │ … │
    │ Don’t know/refused      │    15 │      14 │      15 │      11 │      10 │ … │
    │ Evangelical Prot        │   575 │     869 │    1064 │     982 │     881 │ … │
    │ Hindu                   │     1 │       9 │       7 │       9 │      11 │ … │
    │ Historically Black Prot │   228 │     244 │     236 │     238 │     197 │ … │
    │ Jehovah's Witness       │    20 │      27 │      24 │      24 │      21 │ … │
    │ Jewish                  │    19 │      19 │      25 │      25 │      30 │ … │
    │ …                       │     … │       … │       … │       … │       … │ … │
    └─────────────────────────┴───────┴─────────┴─────────┴─────────┴─────────┴───┘

    Here we convert column names not matching the selector for the `religion` column
    and convert those names into values

    >>> relig_income.pivot_longer(~s.c("religion"), names_to="income", values_to="count")
    ┏━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┓
    ┃ religion ┃ income             ┃ count ┃
    ┡━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━╇━━━━━━━┩
    │ string   │ string             │ int64 │
    ├──────────┼────────────────────┼───────┤
    │ Agnostic │ <$10k              │    27 │
    │ Agnostic │ $10-20k            │    34 │
    │ Agnostic │ $20-30k            │    60 │
    │ Agnostic │ $30-40k            │    81 │
    │ Agnostic │ $40-50k            │    76 │
    │ Agnostic │ $50-75k            │   137 │
    │ Agnostic │ $75-100k           │   122 │
    │ Agnostic │ $100-150k          │   109 │
    │ Agnostic │ >150k              │    84 │
    │ Agnostic │ Don't know/refused │    96 │
    │ …        │ …                  │     … │
    └──────────┴────────────────────┴───────┘

    Similarly for a different example dataset, we convert names to values
    but using a different selector and the default `values_to` value.

    >>> world_bank_pop = ibis.examples.world_bank_pop_raw.fetch()
    >>> world_bank_pop.head()
    ┏━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━┓
    ┃ country ┃ indicator   ┃ 2000         ┃ 2001         ┃ 2002         ┃ … ┃
    ┡━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━┩
    │ string  │ string      │ float64      │ float64      │ float64      │ … │
    ├─────────┼─────────────┼──────────────┼──────────────┼──────────────┼───┤
    │ ABW     │ SP.URB.TOTL │ 4.244400e+04 │ 4.304800e+04 │ 4.367000e+04 │ … │
    │ ABW     │ SP.URB.GROW │ 1.182632e+00 │ 1.413021e+00 │ 1.434560e+00 │ … │
    │ ABW     │ SP.POP.TOTL │ 9.085300e+04 │ 9.289800e+04 │ 9.499200e+04 │ … │
    │ ABW     │ SP.POP.GROW │ 2.055027e+00 │ 2.225930e+00 │ 2.229056e+00 │ … │
    │ AFG     │ SP.URB.TOTL │ 4.436299e+06 │ 4.648055e+06 │ 4.892951e+06 │ … │
    └─────────┴─────────────┴──────────────┴──────────────┴──────────────┴───┘
    >>> world_bank_pop.pivot_longer(s.matches(r"\\d{4}"), names_to="year").head()
    ┏━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━┓
    ┃ country ┃ indicator   ┃ year   ┃ value   ┃
    ┡━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━┩
    │ string  │ string      │ string │ float64 │
    ├─────────┼─────────────┼────────┼─────────┤
    │ ABW     │ SP.URB.TOTL │ 2000   │ 42444.0 │
    │ ABW     │ SP.URB.TOTL │ 2001   │ 43048.0 │
    │ ABW     │ SP.URB.TOTL │ 2002   │ 43670.0 │
    │ ABW     │ SP.URB.TOTL │ 2003   │ 44246.0 │
    │ ABW     │ SP.URB.TOTL │ 2004   │ 44669.0 │
    └─────────┴─────────────┴────────┴─────────┘

    `pivot_longer` has some preprocessing capabiltiies like stripping a prefix and applying
    a function to column names

    >>> billboard = ibis.examples.billboard.fetch()
    >>> billboard
    ┏━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━┓
    ┃ artist         ┃ track                   ┃ date_entered ┃ wk1   ┃ wk2   ┃ … ┃
    ┡━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━┩
    │ string         │ string                  │ date         │ int64 │ int64 │ … │
    ├────────────────┼─────────────────────────┼──────────────┼───────┼───────┼───┤
    │ 2 Pac          │ Baby Don't Cry (Keep... │ 2000-02-26   │    87 │    82 │ … │
    │ 2Ge+her        │ The Hardest Part Of ... │ 2000-09-02   │    91 │    87 │ … │
    │ 3 Doors Down   │ Kryptonite              │ 2000-04-08   │    81 │    70 │ … │
    │ 3 Doors Down   │ Loser                   │ 2000-10-21   │    76 │    76 │ … │
    │ 504 Boyz       │ Wobble Wobble           │ 2000-04-15   │    57 │    34 │ … │
    │ 98^0           │ Give Me Just One Nig... │ 2000-08-19   │    51 │    39 │ … │
    │ A*Teens        │ Dancing Queen           │ 2000-07-08   │    97 │    97 │ … │
    │ Aaliyah        │ I Don't Wanna           │ 2000-01-29   │    84 │    62 │ … │
    │ Aaliyah        │ Try Again               │ 2000-03-18   │    59 │    53 │ … │
    │ Adams, Yolanda │ Open My Heart           │ 2000-08-26   │    76 │    76 │ … │
    │ …              │ …                       │ …            │     … │     … │ … │
    └────────────────┴─────────────────────────┴──────────────┴───────┴───────┴───┘
    >>> billboard.pivot_longer(
    ...     s.startswith("wk"),
    ...     names_to="week",
    ...     names_pattern=r"wk(.+)",
    ...     names_transform=int,
    ...     values_to="rank",
    ...     values_transform=_.cast("int"),
    ... ).dropna("rank")
    ┏━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━┓
    ┃ artist  ┃ track                   ┃ date_entered ┃ week ┃ rank  ┃
    ┡━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━┩
    │ string  │ string                  │ date         │ int8 │ int64 │
    ├─────────┼─────────────────────────┼──────────────┼──────┼───────┤
    │ 2 Pac   │ Baby Don't Cry (Keep... │ 2000-02-26   │    1 │    87 │
    │ 2 Pac   │ Baby Don't Cry (Keep... │ 2000-02-26   │    2 │    82 │
    │ 2 Pac   │ Baby Don't Cry (Keep... │ 2000-02-26   │    3 │    72 │
    │ 2 Pac   │ Baby Don't Cry (Keep... │ 2000-02-26   │    4 │    77 │
    │ 2 Pac   │ Baby Don't Cry (Keep... │ 2000-02-26   │    5 │    87 │
    │ 2 Pac   │ Baby Don't Cry (Keep... │ 2000-02-26   │    6 │    94 │
    │ 2 Pac   │ Baby Don't Cry (Keep... │ 2000-02-26   │    7 │    99 │
    │ 2Ge+her │ The Hardest Part Of ... │ 2000-09-02   │    1 │    91 │
    │ 2Ge+her │ The Hardest Part Of ... │ 2000-09-02   │    2 │    87 │
    │ 2Ge+her │ The Hardest Part Of ... │ 2000-09-02   │    3 │    92 │
    │ …       │ …                       │ …            │    … │     … │
    └─────────┴─────────────────────────┴──────────────┴──────┴───────┘

    You can use regular expression capture groups to extract multiple
    variables stored in column names

    >>> who = ibis.examples.who.fetch()
    >>> who
    ┏━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━┓
    ┃ country     ┃ iso2   ┃ iso3   ┃ year  ┃ new_sp_m014 ┃ new_sp_m1524 ┃ … ┃
    ┡━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━┩
    │ string      │ string │ string │ int64 │ int64       │ int64        │ … │
    ├─────────────┼────────┼────────┼───────┼─────────────┼──────────────┼───┤
    │ Afghanistan │ AF     │ AFG    │  1980 │        NULL │         NULL │ … │
    │ Afghanistan │ AF     │ AFG    │  1981 │        NULL │         NULL │ … │
    │ Afghanistan │ AF     │ AFG    │  1982 │        NULL │         NULL │ … │
    │ Afghanistan │ AF     │ AFG    │  1983 │        NULL │         NULL │ … │
    │ Afghanistan │ AF     │ AFG    │  1984 │        NULL │         NULL │ … │
    │ Afghanistan │ AF     │ AFG    │  1985 │        NULL │         NULL │ … │
    │ Afghanistan │ AF     │ AFG    │  1986 │        NULL │         NULL │ … │
    │ Afghanistan │ AF     │ AFG    │  1987 │        NULL │         NULL │ … │
    │ Afghanistan │ AF     │ AFG    │  1988 │        NULL │         NULL │ … │
    │ Afghanistan │ AF     │ AFG    │  1989 │        NULL │         NULL │ … │
    │ …           │ …      │ …      │     … │           … │            … │ … │
    └─────────────┴────────┴────────┴───────┴─────────────┴──────────────┴───┘
    >>> len(who.columns)
    60
    >>> who.pivot_longer(
    ...     s.r["new_sp_m014":"newrel_f65"],
    ...     names_to=["diagnosis", "gender", "age"],
    ...     names_pattern="new_?(.*)_(.)(.*)",
    ...     values_to="count",
    ... )
    ┏━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━┓
    ┃ country     ┃ iso2   ┃ iso3   ┃ year  ┃ diagnosis ┃ gender ┃ age    ┃ count ┃
    ┡━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━┩
    │ string      │ string │ string │ int64 │ string    │ string │ string │ int64 │
    ├─────────────┼────────┼────────┼───────┼───────────┼────────┼────────┼───────┤
    │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ m      │ 014    │  NULL │
    │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ m      │ 1524   │  NULL │
    │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ m      │ 2534   │  NULL │
    │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ m      │ 3544   │  NULL │
    │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ m      │ 4554   │  NULL │
    │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ m      │ 5564   │  NULL │
    │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ m      │ 65     │  NULL │
    │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ f      │ 014    │  NULL │
    │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ f      │ 1524   │  NULL │
    │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │ f      │ 2534   │  NULL │
    │ …           │ …      │ …      │     … │ …         │ …      │ …      │     … │
    └─────────────┴────────┴────────┴───────┴───────────┴────────┴────────┴───────┘

    `names_transform` is flexible, and can be:

        1. A mapping of one or more names in `names_to` to callable
        2. A callable that will be applied to every name

    Let's recode gender and age to numeric values using a mapping

    >>> who.pivot_longer(
    ...     s.r["new_sp_m014":"newrel_f65"],
    ...     names_to=["diagnosis", "gender", "age"],
    ...     names_pattern="new_?(.*)_(.)(.*)",
    ...     names_transform=dict(
    ...         gender={"m": 1, "f": 2}.get,
    ...         age=dict(zip(["014", "1524", "2534", "3544", "4554", "5564", "65"], range(7))).get,
    ...     ),
    ...     values_to="count",
    ... )
    ┏━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━┳━━━━━━┳━━━━━━━┓
    ┃ country     ┃ iso2   ┃ iso3   ┃ year  ┃ diagnosis ┃ gender ┃ age  ┃ count ┃
    ┡━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━╇━━━━━━╇━━━━━━━┩
    │ string      │ string │ string │ int64 │ string    │ int8   │ int8 │ int64 │
    ├─────────────┼────────┼────────┼───────┼───────────┼────────┼──────┼───────┤
    │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      1 │    0 │  NULL │
    │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      1 │    1 │  NULL │
    │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      1 │    2 │  NULL │
    │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      1 │    3 │  NULL │
    │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      1 │    4 │  NULL │
    │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      1 │    5 │  NULL │
    │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      1 │    6 │  NULL │
    │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      2 │    0 │  NULL │
    │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      2 │    1 │  NULL │
    │ Afghanistan │ AF     │ AFG    │  1980 │ sp        │      2 │    2 │  NULL │
    │ …           │ …      │ …      │     … │ …         │      … │    … │     … │
    └─────────────┴────────┴────────┴───────┴───────────┴────────┴──────┴───────┘

    The number of match groups in `names_pattern` must match the length of `names_to`

    >>> who.pivot_longer(
    ...     s.r["new_sp_m014":"newrel_f65"],
    ...     names_to=["diagnosis", "gender", "age"],
    ...     names_pattern="new_?(.*)_.(.*)",
    ... )
    Traceback (most recent call last):
      ...
    ibis.common.exceptions.IbisInputError: Number of match groups in `names_pattern` ...

    `names_transform` must be a mapping or callable

    >>> who.pivot_longer(s.r["new_sp_m014":"newrel_f65"], names_transform="upper")
    Traceback (most recent call last):
      ...
    ibis.common.exceptions.IbisTypeError: ... Got <class 'str'>
    """
    import ibis.selectors as s

    pivot_sel = s.c(col) if isinstance(col, str) else col

    pivot_cols = pivot_sel.expand(self)
    if not pivot_cols:
        # TODO: improve the repr of selectors
        raise com.IbisInputError("Selector returned no columns to pivot on")

    names_to = util.promote_list(names_to)

    names_pattern = re.compile(names_pattern)
    if (ngroups := names_pattern.groups) != (nnames := len(names_to)):
        raise com.IbisInputError(
            f"Number of match groups in `names_pattern`"
            f"{names_pattern.pattern!r} ({ngroups:d} groups) doesn't "
            f"match the length of `names_to` {names_to} (length {nnames:d})"
        )

    if names_transform is None:
        names_transform = dict.fromkeys(names_to, toolz.identity)
    elif not isinstance(names_transform, Mapping):
        if callable(names_transform):
            names_transform = dict.fromkeys(names_to, names_transform)
        else:
            raise com.IbisTypeError(
                f"`names_transform` must be a mapping or callable. Got {type(names_transform)}"
            )

    for name in names_to:
        names_transform.setdefault(name, toolz.identity)

    if values_transform is None:
        values_transform = toolz.identity
    elif isinstance(values_transform, Deferred):
        values_transform = values_transform.resolve

    pieces = []

    for pivot_col in pivot_cols:
        col_name = pivot_col.get_name()
        match_result = names_pattern.match(col_name)
        row = {
            name: names_transform[name](value)
            for name, value in zip(names_to, match_result.groups())
        }
        row[values_to] = values_transform(pivot_col)
        pieces.append(ibis.struct(row))

    # nest into an array of structs to zip unnests together
    pieces = ibis.array(pieces)

    return self.select(~pivot_sel, __pivoted__=pieces.unnest()).unpack(
        "__pivoted__"
    )

pivot_wider(*, id_cols=None, names_from='name', names_prefix='', names_sep='_', names_sort=False, names=None, values_from='value', values_fill=None, values_agg='arbitrary')

Pivot a table to a wider format.

Parameters:

Name Type Description Default
id_cols s.Selector | None

A set of columns that uniquely identify each observation.

None
names_from str | Iterable[str] | s.Selector

An argument describing which column or columns to use to get the name of the output columns.

'name'
names_prefix str

String added to the start of every column name.

''
names_sep str

If names_from or values_from contains multiple columns, this argument will be used to join their values together into a single string to use as a column name.

'_'
names_sort bool

If True columns are sorted. If False column names are ordered by appearance.

False
names Iterable[str] | None

An explicit sequence of values to look for in columns matching names_from.

  • When this value is None, the values will be computed from names_from.
  • When this value is not None, each element's length must match the length of names_from.

See examples below for more detail.

None
values_from str | Iterable[str] | s.Selector

An argument describing which column or columns to get the cell values from.

'value'
values_fill int | float | str | ir.Scalar | None

A scalar value that specifies what each value should be filled with when missing.

None
values_agg str | Callable[[ir.Value], ir.Scalar] | Deferred

A function applied to the value in each cell in the output.

'arbitrary'

Returns:

Type Description
Table

Wider pivoted table

Examples:

>>> import ibis
>>> import ibis.selectors as s
>>> from ibis import _
>>> ibis.options.interactive = True

Basic usage

>>> fish_encounters = ibis.examples.fish_encounters.fetch()
>>> fish_encounters
┏━━━━━━━┳━━━━━━━━━┳━━━━━━━┓
┃ fish  ┃ station ┃ seen  ┃
┡━━━━━━━╇━━━━━━━━━╇━━━━━━━┩
│ int64 │ string  │ int64 │
├───────┼─────────┼───────┤
│  4842 │ Release │     1 │
│  4842 │ I80_1   │     1 │
│  4842 │ Lisbon  │     1 │
│  4842 │ Rstr    │     1 │
│  4842 │ Base_TD │     1 │
│  4842 │ BCE     │     1 │
│  4842 │ BCW     │     1 │
│  4842 │ BCE2    │     1 │
│  4842 │ BCW2    │     1 │
│  4842 │ MAE     │     1 │
│     … │ …       │     … │
└───────┴─────────┴───────┘
>>> fish_encounters.pivot_wider(names_from="station", values_from="seen")
┏━━━━━━━┳━━━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━┓
┃ fish  ┃ Release ┃ I80_1 ┃ Lisbon ┃ Rstr  ┃ Base_TD ┃ BCE   ┃ BCW   ┃ … ┃
┡━━━━━━━╇━━━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━┩
│ int64 │ int64   │ int64 │ int64  │ int64 │ int64   │ int64 │ int64 │ … │
├───────┼─────────┼───────┼────────┼───────┼─────────┼───────┼───────┼───┤
│  4842 │       1 │     1 │      1 │     1 │       1 │     1 │     1 │ … │
│  4843 │       1 │     1 │      1 │     1 │       1 │     1 │     1 │ … │
│  4844 │       1 │     1 │      1 │     1 │       1 │     1 │     1 │ … │
│  4845 │       1 │     1 │      1 │     1 │       1 │  NULL │  NULL │ … │
│  4847 │       1 │     1 │      1 │  NULL │    NULL │  NULL │  NULL │ … │
│  4848 │       1 │     1 │      1 │     1 │    NULL │  NULL │  NULL │ … │
│  4849 │       1 │     1 │   NULL │  NULL │    NULL │  NULL │  NULL │ … │
│  4850 │       1 │     1 │   NULL │     1 │       1 │     1 │     1 │ … │
│  4851 │       1 │     1 │   NULL │  NULL │    NULL │  NULL │  NULL │ … │
│  4854 │       1 │     1 │   NULL │  NULL │    NULL │  NULL │  NULL │ … │
│     … │       … │     … │      … │     … │       … │     … │     … │ … │
└───────┴─────────┴───────┴────────┴───────┴─────────┴───────┴───────┴───┘

Fill missing pivoted values using values_fill

>>> fish_encounters.pivot_wider(names_from="station", values_from="seen", values_fill=0)
┏━━━━━━━┳━━━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━┓
┃ fish  ┃ Release ┃ I80_1 ┃ Lisbon ┃ Rstr  ┃ Base_TD ┃ BCE   ┃ BCW   ┃ … ┃
┡━━━━━━━╇━━━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━┩
│ int64 │ int64   │ int64 │ int64  │ int64 │ int64   │ int64 │ int64 │ … │
├───────┼─────────┼───────┼────────┼───────┼─────────┼───────┼───────┼───┤
│  4842 │       1 │     1 │      1 │     1 │       1 │     1 │     1 │ … │
│  4843 │       1 │     1 │      1 │     1 │       1 │     1 │     1 │ … │
│  4844 │       1 │     1 │      1 │     1 │       1 │     1 │     1 │ … │
│  4845 │       1 │     1 │      1 │     1 │       1 │     0 │     0 │ … │
│  4847 │       1 │     1 │      1 │     0 │       0 │     0 │     0 │ … │
│  4848 │       1 │     1 │      1 │     1 │       0 │     0 │     0 │ … │
│  4849 │       1 │     1 │      0 │     0 │       0 │     0 │     0 │ … │
│  4850 │       1 │     1 │      0 │     1 │       1 │     1 │     1 │ … │
│  4851 │       1 │     1 │      0 │     0 │       0 │     0 │     0 │ … │
│  4854 │       1 │     1 │      0 │     0 │       0 │     0 │     0 │ … │
│     … │       … │     … │      … │     … │       … │     … │     … │ … │
└───────┴─────────┴───────┴────────┴───────┴─────────┴───────┴───────┴───┘

Compute multiple values columns

>>> us_rent_income = ibis.examples.us_rent_income.fetch()
>>> us_rent_income
┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━┓
┃ geoid  ┃ name       ┃ variable ┃ estimate ┃ moe   ┃
┡━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━┩
│ string │ string     │ string   │ int64    │ int64 │
├────────┼────────────┼──────────┼──────────┼───────┤
│ 01     │ Alabama    │ income   │    24476 │   136 │
│ 01     │ Alabama    │ rent     │      747 │     3 │
│ 02     │ Alaska     │ income   │    32940 │   508 │
│ 02     │ Alaska     │ rent     │     1200 │    13 │
│ 04     │ Arizona    │ income   │    27517 │   148 │
│ 04     │ Arizona    │ rent     │      972 │     4 │
│ 05     │ Arkansas   │ income   │    23789 │   165 │
│ 05     │ Arkansas   │ rent     │      709 │     5 │
│ 06     │ California │ income   │    29454 │   109 │
│ 06     │ California │ rent     │     1358 │     3 │
│ …      │ …          │ …        │        … │     … │
└────────┴────────────┴──────────┴──────────┴───────┘
>>> us_rent_income.pivot_wider(names_from="variable", values_from=["estimate", "moe"])
┏━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━┓
┃ geoid  ┃ name                 ┃ estimate_income ┃ moe_income ┃ … ┃
┡━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━┩
│ string │ string               │ int64           │ int64      │ … │
├────────┼──────────────────────┼─────────────────┼────────────┼───┤
│ 01     │ Alabama              │           24476 │        136 │ … │
│ 02     │ Alaska               │           32940 │        508 │ … │
│ 04     │ Arizona              │           27517 │        148 │ … │
│ 05     │ Arkansas             │           23789 │        165 │ … │
│ 06     │ California           │           29454 │        109 │ … │
│ 08     │ Colorado             │           32401 │        109 │ … │
│ 09     │ Connecticut          │           35326 │        195 │ … │
│ 10     │ Delaware             │           31560 │        247 │ … │
│ 11     │ District of Columbia │           43198 │        681 │ … │
│ 12     │ Florida              │           25952 │         70 │ … │
│ …      │ …                    │               … │          … │ … │
└────────┴──────────────────────┴─────────────────┴────────────┴───┘

The column name separator can be changed using the names_sep parameter

>>> us_rent_income.pivot_wider(
...     names_from="variable",
...     names_sep=".",
...     values_from=s.c("estimate", "moe"),
... )
┏━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━┓
┃ geoid  ┃ name                 ┃ estimate.income ┃ moe.income ┃ … ┃
┡━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━┩
│ string │ string               │ int64           │ int64      │ … │
├────────┼──────────────────────┼─────────────────┼────────────┼───┤
│ 01     │ Alabama              │           24476 │        136 │ … │
│ 02     │ Alaska               │           32940 │        508 │ … │
│ 04     │ Arizona              │           27517 │        148 │ … │
│ 05     │ Arkansas             │           23789 │        165 │ … │
│ 06     │ California           │           29454 │        109 │ … │
│ 08     │ Colorado             │           32401 │        109 │ … │
│ 09     │ Connecticut          │           35326 │        195 │ … │
│ 10     │ Delaware             │           31560 │        247 │ … │
│ 11     │ District of Columbia │           43198 │        681 │ … │
│ 12     │ Florida              │           25952 │         70 │ … │
│ …      │ …                    │               … │          … │ … │
└────────┴──────────────────────┴─────────────────┴────────────┴───┘

Supply an alternative function to summarize values

>>> warpbreaks = ibis.examples.warpbreaks.fetch().select("wool", "tension", "breaks")
>>> warpbreaks
┏━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┓
┃ wool   ┃ tension ┃ breaks ┃
┡━━━━━━━━╇━━━━━━━━━╇━━━━━━━━┩
│ string │ string  │ int64  │
├────────┼─────────┼────────┤
│ A      │ L       │     26 │
│ A      │ L       │     30 │
│ A      │ L       │     54 │
│ A      │ L       │     25 │
│ A      │ L       │     70 │
│ A      │ L       │     52 │
│ A      │ L       │     51 │
│ A      │ L       │     26 │
│ A      │ L       │     67 │
│ A      │ M       │     18 │
│ …      │ …       │      … │
└────────┴─────────┴────────┘
>>> warpbreaks.pivot_wider(names_from="wool", values_from="breaks", values_agg="mean")
┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━┓
┃ tension ┃ A         ┃ B         ┃
┡━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━┩
│ string  │ float64   │ float64   │
├─────────┼───────────┼───────────┤
│ L       │ 44.555556 │ 28.222222 │
│ M       │ 24.000000 │ 28.777778 │
│ H       │ 24.555556 │ 18.777778 │
└─────────┴───────────┴───────────┘

Passing Deferred objects to values_agg is supported

>>> warpbreaks.pivot_wider(
...     names_from="tension",
...     values_from="breaks",
...     values_agg=_.sum(),
... )
┏━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━┓
┃ wool   ┃ L     ┃ M     ┃ H     ┃
┡━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━━━━━┩
│ string │ int64 │ int64 │ int64 │
├────────┼───────┼───────┼───────┤
│ A      │   401 │   216 │   221 │
│ B      │   254 │   259 │   169 │
└────────┴───────┴───────┴───────┘

Use a custom aggregate function

>>> warpbreaks.pivot_wider(
...     names_from="wool",
...     values_from="breaks",
...     values_agg=lambda col: col.std() / col.mean(),
... )
┏━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┓
┃ tension ┃ A        ┃ B        ┃
┡━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━┩
│ string  │ float64  │ float64  │
├─────────┼──────────┼──────────┤
│ L       │ 0.406183 │ 0.349325 │
│ M       │ 0.360844 │ 0.327719 │
│ H       │ 0.418344 │ 0.260590 │
└─────────┴──────────┴──────────┘

Generate some random data, setting the random seed for reproducibility

>>> import random
>>> random.seed(0)
>>> raw = ibis.memtable(
...     [
...         dict(
...             product=product,
...             country=country,
...             year=year,
...             production=random.random(),
...         )
...         for product in "AB"
...         for country in ["AI", "EI"]
...         for year in range(2000, 2015)
...     ]
... )
>>> production = raw.filter(
...     ((_.product == "A") & (_.country == "AI")) | (_.product == "B")
... )
>>> production
┏━━━━━━━━━┳━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━┓
┃ product ┃ country ┃ year  ┃ production ┃
┡━━━━━━━━━╇━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━┩
│ string  │ string  │ int64 │ float64    │
├─────────┼─────────┼───────┼────────────┤
│ B       │ AI      │  2000 │   0.477010 │
│ B       │ AI      │  2001 │   0.865310 │
│ B       │ AI      │  2002 │   0.260492 │
│ B       │ AI      │  2003 │   0.805028 │
│ B       │ AI      │  2004 │   0.548699 │
│ B       │ AI      │  2005 │   0.014042 │
│ B       │ AI      │  2006 │   0.719705 │
│ B       │ AI      │  2007 │   0.398824 │
│ B       │ AI      │  2008 │   0.824845 │
│ B       │ AI      │  2009 │   0.668153 │
│ …       │ …       │     … │          … │
└─────────┴─────────┴───────┴────────────┘

Pivoting with multiple name columns

>>> production.pivot_wider(
...     names_from=["product", "country"],
...     values_from="production",
... )
┏━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┓
┃ year  ┃ B_AI     ┃ B_EI     ┃ A_AI     ┃
┡━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━┩
│ int64 │ float64  │ float64  │ float64  │
├───────┼──────────┼──────────┼──────────┤
│  2000 │ 0.477010 │ 0.870471 │ 0.844422 │
│  2001 │ 0.865310 │ 0.191067 │ 0.757954 │
│  2002 │ 0.260492 │ 0.567511 │ 0.420572 │
│  2003 │ 0.805028 │ 0.238616 │ 0.258917 │
│  2004 │ 0.548699 │ 0.967540 │ 0.511275 │
│  2005 │ 0.014042 │ 0.803179 │ 0.404934 │
│  2006 │ 0.719705 │ 0.447970 │ 0.783799 │
│  2007 │ 0.398824 │ 0.080446 │ 0.303313 │
│  2008 │ 0.824845 │ 0.320055 │ 0.476597 │
│  2009 │ 0.668153 │ 0.507941 │ 0.583382 │
│     … │        … │        … │        … │
└───────┴──────────┴──────────┴──────────┘

Select a subset of names. This call incurs no computation when constructing the expression.

>>> production.pivot_wider(
...     names_from=["product", "country"],
...     names=[("A", "AI"), ("B", "AI")],
...     values_from="production",
... )
┏━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┓
┃ year  ┃ A_AI     ┃ B_AI     ┃
┡━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━┩
│ int64 │ float64  │ float64  │
├───────┼──────────┼──────────┤
│  2000 │ 0.844422 │ 0.477010 │
│  2001 │ 0.757954 │ 0.865310 │
│  2002 │ 0.420572 │ 0.260492 │
│  2003 │ 0.258917 │ 0.805028 │
│  2004 │ 0.511275 │ 0.548699 │
│  2005 │ 0.404934 │ 0.014042 │
│  2006 │ 0.783799 │ 0.719705 │
│  2007 │ 0.303313 │ 0.398824 │
│  2008 │ 0.476597 │ 0.824845 │
│  2009 │ 0.583382 │ 0.668153 │
│     … │        … │        … │
└───────┴──────────┴──────────┘

Sort the new columns' names

>>> production.pivot_wider(
...     names_from=["product", "country"],
...     values_from="production",
...     names_sort=True,
... )
┏━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┓
┃ year  ┃ A_AI     ┃ B_AI     ┃ B_EI     ┃
┡━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━┩
│ int64 │ float64  │ float64  │ float64  │
├───────┼──────────┼──────────┼──────────┤
│  2000 │ 0.844422 │ 0.477010 │ 0.870471 │
│  2001 │ 0.757954 │ 0.865310 │ 0.191067 │
│  2002 │ 0.420572 │ 0.260492 │ 0.567511 │
│  2003 │ 0.258917 │ 0.805028 │ 0.238616 │
│  2004 │ 0.511275 │ 0.548699 │ 0.967540 │
│  2005 │ 0.404934 │ 0.014042 │ 0.803179 │
│  2006 │ 0.783799 │ 0.719705 │ 0.447970 │
│  2007 │ 0.303313 │ 0.398824 │ 0.080446 │
│  2008 │ 0.476597 │ 0.824845 │ 0.320055 │
│  2009 │ 0.583382 │ 0.668153 │ 0.507941 │
│     … │        … │        … │        … │
└───────┴──────────┴──────────┴──────────┘
Source code in ibis/expr/types/relations.py
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
@util.experimental
def pivot_wider(
    self,
    *,
    id_cols: s.Selector | None = None,
    names_from: str | Iterable[str] | s.Selector = "name",
    names_prefix: str = "",
    names_sep: str = "_",
    names_sort: bool = False,
    names: Iterable[str] | None = None,
    values_from: str | Iterable[str] | s.Selector = "value",
    values_fill: int | float | str | ir.Scalar | None = None,
    values_agg: str | Callable[[ir.Value], ir.Scalar] | Deferred = "arbitrary",
):
    """Pivot a table to a wider format.

    Parameters
    ----------
    id_cols
        A set of columns that uniquely identify each observation.
    names_from
        An argument describing which column or columns to use to get the
        name of the output columns.
    names_prefix
        String added to the start of every column name.
    names_sep
        If `names_from` or `values_from` contains multiple columns, this
        argument will be used to join their values together into a single
        string to use as a column name.
    names_sort
        If [`True`][True] columns are sorted. If [`False`][False] column
        names are ordered by appearance.
    names
        An explicit sequence of values to look for in columns matching
        `names_from`.

        * When this value is `None`, the values will be computed from
          `names_from`.
        * When this value is not `None`, each element's length must match
          the length of `names_from`.

        See examples below for more detail.
    values_from
        An argument describing which column or columns to get the cell
        values from.
    values_fill
        A scalar value that specifies what each value should be filled with
        when missing.
    values_agg
        A function applied to the value in each cell in the output.

    Returns
    -------
    Table
        Wider pivoted table

    Examples
    --------
    >>> import ibis
    >>> import ibis.selectors as s
    >>> from ibis import _
    >>> ibis.options.interactive = True

    Basic usage

    >>> fish_encounters = ibis.examples.fish_encounters.fetch()
    >>> fish_encounters
    ┏━━━━━━━┳━━━━━━━━━┳━━━━━━━┓
    ┃ fish  ┃ station ┃ seen  ┃
    ┡━━━━━━━╇━━━━━━━━━╇━━━━━━━┩
    │ int64 │ string  │ int64 │
    ├───────┼─────────┼───────┤
    │  4842 │ Release │     1 │
    │  4842 │ I80_1   │     1 │
    │  4842 │ Lisbon  │     1 │
    │  4842 │ Rstr    │     1 │
    │  4842 │ Base_TD │     1 │
    │  4842 │ BCE     │     1 │
    │  4842 │ BCW     │     1 │
    │  4842 │ BCE2    │     1 │
    │  4842 │ BCW2    │     1 │
    │  4842 │ MAE     │     1 │
    │     … │ …       │     … │
    └───────┴─────────┴───────┘
    >>> fish_encounters.pivot_wider(names_from="station", values_from="seen")
    ┏━━━━━━━┳━━━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━┓
    ┃ fish  ┃ Release ┃ I80_1 ┃ Lisbon ┃ Rstr  ┃ Base_TD ┃ BCE   ┃ BCW   ┃ … ┃
    ┡━━━━━━━╇━━━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━┩
    │ int64 │ int64   │ int64 │ int64  │ int64 │ int64   │ int64 │ int64 │ … │
    ├───────┼─────────┼───────┼────────┼───────┼─────────┼───────┼───────┼───┤
    │  4842 │       1 │     1 │      1 │     1 │       1 │     1 │     1 │ … │
    │  4843 │       1 │     1 │      1 │     1 │       1 │     1 │     1 │ … │
    │  4844 │       1 │     1 │      1 │     1 │       1 │     1 │     1 │ … │
    │  4845 │       1 │     1 │      1 │     1 │       1 │  NULL │  NULL │ … │
    │  4847 │       1 │     1 │      1 │  NULL │    NULL │  NULL │  NULL │ … │
    │  4848 │       1 │     1 │      1 │     1 │    NULL │  NULL │  NULL │ … │
    │  4849 │       1 │     1 │   NULL │  NULL │    NULL │  NULL │  NULL │ … │
    │  4850 │       1 │     1 │   NULL │     1 │       1 │     1 │     1 │ … │
    │  4851 │       1 │     1 │   NULL │  NULL │    NULL │  NULL │  NULL │ … │
    │  4854 │       1 │     1 │   NULL │  NULL │    NULL │  NULL │  NULL │ … │
    │     … │       … │     … │      … │     … │       … │     … │     … │ … │
    └───────┴─────────┴───────┴────────┴───────┴─────────┴───────┴───────┴───┘

    Fill missing pivoted values using `values_fill`

    >>> fish_encounters.pivot_wider(names_from="station", values_from="seen", values_fill=0)
    ┏━━━━━━━┳━━━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━┓
    ┃ fish  ┃ Release ┃ I80_1 ┃ Lisbon ┃ Rstr  ┃ Base_TD ┃ BCE   ┃ BCW   ┃ … ┃
    ┡━━━━━━━╇━━━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━┩
    │ int64 │ int64   │ int64 │ int64  │ int64 │ int64   │ int64 │ int64 │ … │
    ├───────┼─────────┼───────┼────────┼───────┼─────────┼───────┼───────┼───┤
    │  4842 │       1 │     1 │      1 │     1 │       1 │     1 │     1 │ … │
    │  4843 │       1 │     1 │      1 │     1 │       1 │     1 │     1 │ … │
    │  4844 │       1 │     1 │      1 │     1 │       1 │     1 │     1 │ … │
    │  4845 │       1 │     1 │      1 │     1 │       1 │     0 │     0 │ … │
    │  4847 │       1 │     1 │      1 │     0 │       0 │     0 │     0 │ … │
    │  4848 │       1 │     1 │      1 │     1 │       0 │     0 │     0 │ … │
    │  4849 │       1 │     1 │      0 │     0 │       0 │     0 │     0 │ … │
    │  4850 │       1 │     1 │      0 │     1 │       1 │     1 │     1 │ … │
    │  4851 │       1 │     1 │      0 │     0 │       0 │     0 │     0 │ … │
    │  4854 │       1 │     1 │      0 │     0 │       0 │     0 │     0 │ … │
    │     … │       … │     … │      … │     … │       … │     … │     … │ … │
    └───────┴─────────┴───────┴────────┴───────┴─────────┴───────┴───────┴───┘

    Compute multiple values columns

    >>> us_rent_income = ibis.examples.us_rent_income.fetch()
    >>> us_rent_income
    ┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━┓
    ┃ geoid  ┃ name       ┃ variable ┃ estimate ┃ moe   ┃
    ┡━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━┩
    │ string │ string     │ string   │ int64    │ int64 │
    ├────────┼────────────┼──────────┼──────────┼───────┤
    │ 01     │ Alabama    │ income   │    24476 │   136 │
    │ 01     │ Alabama    │ rent     │      747 │     3 │
    │ 02     │ Alaska     │ income   │    32940 │   508 │
    │ 02     │ Alaska     │ rent     │     1200 │    13 │
    │ 04     │ Arizona    │ income   │    27517 │   148 │
    │ 04     │ Arizona    │ rent     │      972 │     4 │
    │ 05     │ Arkansas   │ income   │    23789 │   165 │
    │ 05     │ Arkansas   │ rent     │      709 │     5 │
    │ 06     │ California │ income   │    29454 │   109 │
    │ 06     │ California │ rent     │     1358 │     3 │
    │ …      │ …          │ …        │        … │     … │
    └────────┴────────────┴──────────┴──────────┴───────┘
    >>> us_rent_income.pivot_wider(names_from="variable", values_from=["estimate", "moe"])
    ┏━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━┓
    ┃ geoid  ┃ name                 ┃ estimate_income ┃ moe_income ┃ … ┃
    ┡━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━┩
    │ string │ string               │ int64           │ int64      │ … │
    ├────────┼──────────────────────┼─────────────────┼────────────┼───┤
    │ 01     │ Alabama              │           24476 │        136 │ … │
    │ 02     │ Alaska               │           32940 │        508 │ … │
    │ 04     │ Arizona              │           27517 │        148 │ … │
    │ 05     │ Arkansas             │           23789 │        165 │ … │
    │ 06     │ California           │           29454 │        109 │ … │
    │ 08     │ Colorado             │           32401 │        109 │ … │
    │ 09     │ Connecticut          │           35326 │        195 │ … │
    │ 10     │ Delaware             │           31560 │        247 │ … │
    │ 11     │ District of Columbia │           43198 │        681 │ … │
    │ 12     │ Florida              │           25952 │         70 │ … │
    │ …      │ …                    │               … │          … │ … │
    └────────┴──────────────────────┴─────────────────┴────────────┴───┘

    The column name separator can be changed using the `names_sep` parameter

    >>> us_rent_income.pivot_wider(
    ...     names_from="variable",
    ...     names_sep=".",
    ...     values_from=s.c("estimate", "moe"),
    ... )
    ┏━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━┓
    ┃ geoid  ┃ name                 ┃ estimate.income ┃ moe.income ┃ … ┃
    ┡━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━┩
    │ string │ string               │ int64           │ int64      │ … │
    ├────────┼──────────────────────┼─────────────────┼────────────┼───┤
    │ 01     │ Alabama              │           24476 │        136 │ … │
    │ 02     │ Alaska               │           32940 │        508 │ … │
    │ 04     │ Arizona              │           27517 │        148 │ … │
    │ 05     │ Arkansas             │           23789 │        165 │ … │
    │ 06     │ California           │           29454 │        109 │ … │
    │ 08     │ Colorado             │           32401 │        109 │ … │
    │ 09     │ Connecticut          │           35326 │        195 │ … │
    │ 10     │ Delaware             │           31560 │        247 │ … │
    │ 11     │ District of Columbia │           43198 │        681 │ … │
    │ 12     │ Florida              │           25952 │         70 │ … │
    │ …      │ …                    │               … │          … │ … │
    └────────┴──────────────────────┴─────────────────┴────────────┴───┘

    Supply an alternative function to summarize values

    >>> warpbreaks = ibis.examples.warpbreaks.fetch().select("wool", "tension", "breaks")
    >>> warpbreaks
    ┏━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┓
    ┃ wool   ┃ tension ┃ breaks ┃
    ┡━━━━━━━━╇━━━━━━━━━╇━━━━━━━━┩
    │ string │ string  │ int64  │
    ├────────┼─────────┼────────┤
    │ A      │ L       │     26 │
    │ A      │ L       │     30 │
    │ A      │ L       │     54 │
    │ A      │ L       │     25 │
    │ A      │ L       │     70 │
    │ A      │ L       │     52 │
    │ A      │ L       │     51 │
    │ A      │ L       │     26 │
    │ A      │ L       │     67 │
    │ A      │ M       │     18 │
    │ …      │ …       │      … │
    └────────┴─────────┴────────┘
    >>> warpbreaks.pivot_wider(names_from="wool", values_from="breaks", values_agg="mean")
    ┏━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━┓
    ┃ tension ┃ A         ┃ B         ┃
    ┡━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━┩
    │ string  │ float64   │ float64   │
    ├─────────┼───────────┼───────────┤
    │ L       │ 44.555556 │ 28.222222 │
    │ M       │ 24.000000 │ 28.777778 │
    │ H       │ 24.555556 │ 18.777778 │
    └─────────┴───────────┴───────────┘

    Passing `Deferred` objects to `values_agg` is supported

    >>> warpbreaks.pivot_wider(
    ...     names_from="tension",
    ...     values_from="breaks",
    ...     values_agg=_.sum(),
    ... )
    ┏━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━┓
    ┃ wool   ┃ L     ┃ M     ┃ H     ┃
    ┡━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━━━━━┩
    │ string │ int64 │ int64 │ int64 │
    ├────────┼───────┼───────┼───────┤
    │ A      │   401 │   216 │   221 │
    │ B      │   254 │   259 │   169 │
    └────────┴───────┴───────┴───────┘

    Use a custom aggregate function

    >>> warpbreaks.pivot_wider(
    ...     names_from="wool",
    ...     values_from="breaks",
    ...     values_agg=lambda col: col.std() / col.mean(),
    ... )
    ┏━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┓
    ┃ tension ┃ A        ┃ B        ┃
    ┡━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━┩
    │ string  │ float64  │ float64  │
    ├─────────┼──────────┼──────────┤
    │ L       │ 0.406183 │ 0.349325 │
    │ M       │ 0.360844 │ 0.327719 │
    │ H       │ 0.418344 │ 0.260590 │
    └─────────┴──────────┴──────────┘

    Generate some random data, setting the random seed for reproducibility

    >>> import random
    >>> random.seed(0)
    >>> raw = ibis.memtable(
    ...     [
    ...         dict(
    ...             product=product,
    ...             country=country,
    ...             year=year,
    ...             production=random.random(),
    ...         )
    ...         for product in "AB"
    ...         for country in ["AI", "EI"]
    ...         for year in range(2000, 2015)
    ...     ]
    ... )
    >>> production = raw.filter(
    ...     ((_.product == "A") & (_.country == "AI")) | (_.product == "B")
    ... )
    >>> production
    ┏━━━━━━━━━┳━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━┓
    ┃ product ┃ country ┃ year  ┃ production ┃
    ┡━━━━━━━━━╇━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━┩
    │ string  │ string  │ int64 │ float64    │
    ├─────────┼─────────┼───────┼────────────┤
    │ B       │ AI      │  2000 │   0.477010 │
    │ B       │ AI      │  2001 │   0.865310 │
    │ B       │ AI      │  2002 │   0.260492 │
    │ B       │ AI      │  2003 │   0.805028 │
    │ B       │ AI      │  2004 │   0.548699 │
    │ B       │ AI      │  2005 │   0.014042 │
    │ B       │ AI      │  2006 │   0.719705 │
    │ B       │ AI      │  2007 │   0.398824 │
    │ B       │ AI      │  2008 │   0.824845 │
    │ B       │ AI      │  2009 │   0.668153 │
    │ …       │ …       │     … │          … │
    └─────────┴─────────┴───────┴────────────┘

    Pivoting with multiple name columns

    >>> production.pivot_wider(
    ...     names_from=["product", "country"],
    ...     values_from="production",
    ... )
    ┏━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┓
    ┃ year  ┃ B_AI     ┃ B_EI     ┃ A_AI     ┃
    ┡━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━┩
    │ int64 │ float64  │ float64  │ float64  │
    ├───────┼──────────┼──────────┼──────────┤
    │  2000 │ 0.477010 │ 0.870471 │ 0.844422 │
    │  2001 │ 0.865310 │ 0.191067 │ 0.757954 │
    │  2002 │ 0.260492 │ 0.567511 │ 0.420572 │
    │  2003 │ 0.805028 │ 0.238616 │ 0.258917 │
    │  2004 │ 0.548699 │ 0.967540 │ 0.511275 │
    │  2005 │ 0.014042 │ 0.803179 │ 0.404934 │
    │  2006 │ 0.719705 │ 0.447970 │ 0.783799 │
    │  2007 │ 0.398824 │ 0.080446 │ 0.303313 │
    │  2008 │ 0.824845 │ 0.320055 │ 0.476597 │
    │  2009 │ 0.668153 │ 0.507941 │ 0.583382 │
    │     … │        … │        … │        … │
    └───────┴──────────┴──────────┴──────────┘

    Select a subset of names. This call incurs no computation when
    constructing the expression.

    >>> production.pivot_wider(
    ...     names_from=["product", "country"],
    ...     names=[("A", "AI"), ("B", "AI")],
    ...     values_from="production",
    ... )
    ┏━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┓
    ┃ year  ┃ A_AI     ┃ B_AI     ┃
    ┡━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━┩
    │ int64 │ float64  │ float64  │
    ├───────┼──────────┼──────────┤
    │  2000 │ 0.844422 │ 0.477010 │
    │  2001 │ 0.757954 │ 0.865310 │
    │  2002 │ 0.420572 │ 0.260492 │
    │  2003 │ 0.258917 │ 0.805028 │
    │  2004 │ 0.511275 │ 0.548699 │
    │  2005 │ 0.404934 │ 0.014042 │
    │  2006 │ 0.783799 │ 0.719705 │
    │  2007 │ 0.303313 │ 0.398824 │
    │  2008 │ 0.476597 │ 0.824845 │
    │  2009 │ 0.583382 │ 0.668153 │
    │     … │        … │        … │
    └───────┴──────────┴──────────┘

    Sort the new columns' names

    >>> production.pivot_wider(
    ...     names_from=["product", "country"],
    ...     values_from="production",
    ...     names_sort=True,
    ... )
    ┏━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┓
    ┃ year  ┃ A_AI     ┃ B_AI     ┃ B_EI     ┃
    ┡━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━┩
    │ int64 │ float64  │ float64  │ float64  │
    ├───────┼──────────┼──────────┼──────────┤
    │  2000 │ 0.844422 │ 0.477010 │ 0.870471 │
    │  2001 │ 0.757954 │ 0.865310 │ 0.191067 │
    │  2002 │ 0.420572 │ 0.260492 │ 0.567511 │
    │  2003 │ 0.258917 │ 0.805028 │ 0.238616 │
    │  2004 │ 0.511275 │ 0.548699 │ 0.967540 │
    │  2005 │ 0.404934 │ 0.014042 │ 0.803179 │
    │  2006 │ 0.783799 │ 0.719705 │ 0.447970 │
    │  2007 │ 0.303313 │ 0.398824 │ 0.080446 │
    │  2008 │ 0.476597 │ 0.824845 │ 0.320055 │
    │  2009 │ 0.583382 │ 0.668153 │ 0.507941 │
    │     … │        … │        … │        … │
    └───────┴──────────┴──────────┴──────────┘
    """
    import pandas as pd
    import ibis.selectors as s
    import ibis.expr.analysis as an
    from ibis import _

    orig_names_from = util.promote_list(names_from)

    names_from = s.any_of(*map(s._to_selector, orig_names_from))
    values_from = s.any_of(*map(s._to_selector, util.promote_list(values_from)))

    if id_cols is None:
        id_cols = ~(names_from | values_from)
    else:
        id_cols = s._to_selector(id_cols)

    if isinstance(values_agg, str):
        values_agg = operator.methodcaller(values_agg)
    elif isinstance(values_agg, Deferred):
        values_agg = values_agg.resolve

    if names is None:
        # no names provided, compute them from the data
        names = self.select(names_from).distinct().execute()
    else:
        if not (columns := [col.get_name() for col in names_from.expand(self)]):
            raise com.IbisInputError(
                f"No matching names columns in `names_from`: {orig_names_from}"
            )
        names = pd.DataFrame(list(map(util.promote_list, names)), columns=columns)

    if names_sort:
        names = names.sort_values(by=names.columns.tolist())

    values_cols = values_from.expand(self)
    more_than_one_value = len(values_cols) > 1
    aggs = {}

    names_cols_exprs = [self[col] for col in names.columns]

    for keys in names.itertuples(index=False):
        where = ibis.and_(*map(operator.eq, names_cols_exprs, keys))

        for values_col in values_cols:
            arg = values_agg(values_col)

            # add in the where clause to filter the appropriate values
            # in/out
            #
            # this allows users to write the aggregate without having to deal with
            # the filter themselves
            existing_aggs = an.find_toplevel_aggs(arg.op())
            subs = {
                agg: agg.copy(
                    where=(
                        where
                        if (existing := agg.where) is None
                        else where & existing
                    )
                )
                for agg in existing_aggs
            }
            arg = an.sub_for(arg.op(), subs).to_expr()

            # build the components of the group by key
            key_components = (
                # user provided prefix
                names_prefix,
                # include the `values` column name if there's more than one
                # `values` column
                values_col.get_name() * more_than_one_value,
                # values computed from `names`/`names_from`
                *keys,
            )
            key = names_sep.join(filter(None, key_components))
            aggs[key] = arg if values_fill is None else arg.coalesce(values_fill)

    return self.group_by(id_cols).aggregate(**aggs)

relabel(substitutions)

Rename columns in the table.

Parameters:

Name Type Description Default
substitutions Mapping[str, str] | Callable[[str], str | None] | str | Literal['snake_case', 'ALL_CAPS']

A mapping, function, or format string mapping old to new column names. If a column isn't in the mapping (or if the callable returns None) it is left with its original name. May also pass a format string to rename all columns, like "prefix_{name}". Also accepts the literal string "snake_case" or "ALL_CAPS" which will relabel all columns to use a snake_case or "ALL_CAPS" naming convention.

required

Returns:

Type Description
Table

A relabeled table expression

Examples:

>>> import ibis
>>> import ibis.selectors as s
>>> ibis.options.interactive = True
>>> first3 = s.r[:3]  # first 3 columns
>>> t = ibis.examples.penguins_raw_raw.fetch().select(first3)
>>> t
┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ studyName ┃ Sample Number ┃ Species                             ┃
┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ string    │ int64         │ string                              │
├───────────┼───────────────┼─────────────────────────────────────┤
│ PAL0708   │             1 │ Adelie Penguin (Pygoscelis adeliae) │
│ PAL0708   │             2 │ Adelie Penguin (Pygoscelis adeliae) │
│ PAL0708   │             3 │ Adelie Penguin (Pygoscelis adeliae) │
│ PAL0708   │             4 │ Adelie Penguin (Pygoscelis adeliae) │
│ PAL0708   │             5 │ Adelie Penguin (Pygoscelis adeliae) │
│ PAL0708   │             6 │ Adelie Penguin (Pygoscelis adeliae) │
│ PAL0708   │             7 │ Adelie Penguin (Pygoscelis adeliae) │
│ PAL0708   │             8 │ Adelie Penguin (Pygoscelis adeliae) │
│ PAL0708   │             9 │ Adelie Penguin (Pygoscelis adeliae) │
│ PAL0708   │            10 │ Adelie Penguin (Pygoscelis adeliae) │
│ …         │             … │ …                                   │
└───────────┴───────────────┴─────────────────────────────────────┘

Relabel column names using a mapping from old name to new name

>>> t.relabel({"studyName": "study_name"}).head(1)
┏━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ study_name ┃ Sample Number ┃ Species                             ┃
┡━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ string     │ int64         │ string                              │
├────────────┼───────────────┼─────────────────────────────────────┤
│ PAL0708    │             1 │ Adelie Penguin (Pygoscelis adeliae) │
└────────────┴───────────────┴─────────────────────────────────────┘

Relabel column names using a snake_case convention

>>> t.relabel("snake_case").head(1)
┏━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ study_name ┃ sample_number ┃ species                             ┃
┡━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ string     │ int64         │ string                              │
├────────────┼───────────────┼─────────────────────────────────────┤
│ PAL0708    │             1 │ Adelie Penguin (Pygoscelis adeliae) │
└────────────┴───────────────┴─────────────────────────────────────┘

Relabel column names using a ALL_CAPS convention

>>> t.relabel("ALL_CAPS").head(1)
┏━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ STUDY_NAME ┃ SAMPLE_NUMBER ┃ SPECIES                             ┃
┡━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ string     │ int64         │ string                              │
├────────────┼───────────────┼─────────────────────────────────────┤
│ PAL0708    │             1 │ Adelie Penguin (Pygoscelis adeliae) │
└────────────┴───────────────┴─────────────────────────────────────┘

Relabel columns using a format string

>>> t.relabel("p_{name}").head(1)
┏━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ p_studyName ┃ p_Sample Number ┃ p_Species                           ┃
┡━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ string      │ int64           │ string                              │
├─────────────┼─────────────────┼─────────────────────────────────────┤
│ PAL0708     │               1 │ Adelie Penguin (Pygoscelis adeliae) │
└─────────────┴─────────────────┴─────────────────────────────────────┘

Relabel column names using a callable

>>> t.relabel(str.upper).head(1)
┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ STUDYNAME ┃ SAMPLE NUMBER ┃ SPECIES                             ┃
┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ string    │ int64         │ string                              │
├───────────┼───────────────┼─────────────────────────────────────┤
│ PAL0708   │             1 │ Adelie Penguin (Pygoscelis adeliae) │
└───────────┴───────────────┴─────────────────────────────────────┘
Source code in ibis/expr/types/relations.py
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
def relabel(
    self,
    substitutions: Mapping[str, str]
    | Callable[[str], str | None]
    | str
    | Literal["snake_case", "ALL_CAPS"],
) -> Table:
    """Rename columns in the table.

    Parameters
    ----------
    substitutions
        A mapping, function, or format string mapping old to new column
        names. If a column isn't in the mapping (or if the callable returns
        None) it is left with its original name. May also pass a format
        string to rename all columns, like ``"prefix_{name}"``. Also
        accepts the literal string ``"snake_case"`` or ``"ALL_CAPS"`` which
        will relabel all columns to use a ``snake_case`` or ``"ALL_CAPS"``
        naming convention.

    Returns
    -------
    Table
        A relabeled table expression

    Examples
    --------
    >>> import ibis
    >>> import ibis.selectors as s
    >>> ibis.options.interactive = True
    >>> first3 = s.r[:3]  # first 3 columns
    >>> t = ibis.examples.penguins_raw_raw.fetch().select(first3)
    >>> t
    ┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
    ┃ studyName ┃ Sample Number ┃ Species                             ┃
    ┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
    │ string    │ int64         │ string                              │
    ├───────────┼───────────────┼─────────────────────────────────────┤
    │ PAL0708   │             1 │ Adelie Penguin (Pygoscelis adeliae) │
    │ PAL0708   │             2 │ Adelie Penguin (Pygoscelis adeliae) │
    │ PAL0708   │             3 │ Adelie Penguin (Pygoscelis adeliae) │
    │ PAL0708   │             4 │ Adelie Penguin (Pygoscelis adeliae) │
    │ PAL0708   │             5 │ Adelie Penguin (Pygoscelis adeliae) │
    │ PAL0708   │             6 │ Adelie Penguin (Pygoscelis adeliae) │
    │ PAL0708   │             7 │ Adelie Penguin (Pygoscelis adeliae) │
    │ PAL0708   │             8 │ Adelie Penguin (Pygoscelis adeliae) │
    │ PAL0708   │             9 │ Adelie Penguin (Pygoscelis adeliae) │
    │ PAL0708   │            10 │ Adelie Penguin (Pygoscelis adeliae) │
    │ …         │             … │ …                                   │
    └───────────┴───────────────┴─────────────────────────────────────┘

    Relabel column names using a mapping from old name to new name

    >>> t.relabel({"studyName": "study_name"}).head(1)
    ┏━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
    ┃ study_name ┃ Sample Number ┃ Species                             ┃
    ┡━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
    │ string     │ int64         │ string                              │
    ├────────────┼───────────────┼─────────────────────────────────────┤
    │ PAL0708    │             1 │ Adelie Penguin (Pygoscelis adeliae) │
    └────────────┴───────────────┴─────────────────────────────────────┘

    Relabel column names using a snake_case convention

    >>> t.relabel("snake_case").head(1)
    ┏━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
    ┃ study_name ┃ sample_number ┃ species                             ┃
    ┡━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
    │ string     │ int64         │ string                              │
    ├────────────┼───────────────┼─────────────────────────────────────┤
    │ PAL0708    │             1 │ Adelie Penguin (Pygoscelis adeliae) │
    └────────────┴───────────────┴─────────────────────────────────────┘

    Relabel column names using a ALL_CAPS convention

    >>> t.relabel("ALL_CAPS").head(1)
    ┏━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
    ┃ STUDY_NAME ┃ SAMPLE_NUMBER ┃ SPECIES                             ┃
    ┡━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
    │ string     │ int64         │ string                              │
    ├────────────┼───────────────┼─────────────────────────────────────┤
    │ PAL0708    │             1 │ Adelie Penguin (Pygoscelis adeliae) │
    └────────────┴───────────────┴─────────────────────────────────────┘

    Relabel columns using a format string

    >>> t.relabel("p_{name}").head(1)
    ┏━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
    ┃ p_studyName ┃ p_Sample Number ┃ p_Species                           ┃
    ┡━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
    │ string      │ int64           │ string                              │
    ├─────────────┼─────────────────┼─────────────────────────────────────┤
    │ PAL0708     │               1 │ Adelie Penguin (Pygoscelis adeliae) │
    └─────────────┴─────────────────┴─────────────────────────────────────┘

    Relabel column names using a callable

    >>> t.relabel(str.upper).head(1)
    ┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
    ┃ STUDYNAME ┃ SAMPLE NUMBER ┃ SPECIES                             ┃
    ┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
    │ string    │ int64         │ string                              │
    ├───────────┼───────────────┼─────────────────────────────────────┤
    │ PAL0708   │             1 │ Adelie Penguin (Pygoscelis adeliae) │
    └───────────┴───────────────┴─────────────────────────────────────┘
    """
    observed = set()

    if isinstance(substitutions, Mapping):
        rename = substitutions.get
    elif substitutions in {"snake_case", "ALL_CAPS"}:

        def rename(c):
            c = c.strip()
            if " " in c:
                # Handle "space case possibly with-hyphens"
                if substitutions == "snake_case":
                    return "_".join(c.lower().split()).replace("-", "_")
                elif substitutions == "ALL_CAPS":
                    return "_".join(c.upper().split()).replace("-", "_")
            # Handle PascalCase, camelCase, and kebab-case
            c = re.sub(r"([A-Z]+)([A-Z][a-z])", r'\1_\2', c)
            c = re.sub(r"([a-z\d])([A-Z])", r'\1_\2', c)
            c = c.replace("-", "_")
            if substitutions == "snake_case":
                return c.lower()
            elif substitutions == "ALL_CAPS":
                return c.upper()

    elif isinstance(substitutions, str):

        def rename(name):
            return substitutions.format(name=name)

        # Detect the case of missing or extra format string parameters
        try:
            dummy_name1 = "_unlikely_column_name_1_"
            dummy_name2 = "_unlikely_column_name_2_"
            invalid = rename(dummy_name1) == rename(dummy_name2)
        except KeyError:
            invalid = True
        if invalid:
            raise ValueError("Format strings must take a single parameter `name`")
    else:
        rename = substitutions

    exprs = []
    for c in self.columns:
        expr = self[c]
        if (name := rename(c)) is not None:
            expr = expr.name(name)
            observed.add(c)
        exprs.append(expr)

    if isinstance(substitutions, Mapping):
        for c in substitutions:
            if c not in observed:
                raise KeyError(f"{c!r} is not an existing column")

    return self.select(exprs)

rowid()

A unique integer per row.

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 or duckdb's rowid).

For a monotonically increasing row number, see ibis.row_number.

Returns:

Type Description
IntegerColumn

An integer column

Source code in ibis/expr/types/relations.py
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
def rowid(self) -> ir.IntegerValue:
    """A unique integer per row.

    !!! 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 or 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()

schema()

Return the schema for this table.

Returns:

Type Description
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
}
Source code in ibis/expr/types/relations.py
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
def schema(self) -> sch.Schema:
    """Return the 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

select(*exprs, **named_exprs)

Compute a new table expression using exprs and named_exprs.

Passing an aggregate function to this method will broadcast the aggregate's value over the number of rows in the table and automatically constructs a window function expression. See the examples section for more details.

For backwards compatibility the keyword argument exprs is reserved and cannot be used to name an expression. This behavior will be removed in v4.

Parameters:

Name Type Description Default
exprs ir.Value | str | Iterable[ir.Value | str]

Column expression, string, or list of column expressions and strings.

()
named_exprs ir.Value | str

Column expressions

{}

Returns:

Type Description
Table

Table expression

Examples:

>>> import ibis
>>> 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 │            nan │           nan │              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 │ … │
│ …       │ …         │              … │             … │                 … │ … │
└─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘

Simple projection

>>> t.select("island", "bill_length_mm").head()
┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┓
┃ island    ┃ bill_length_mm ┃
┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━━┩
│ string    │ float64        │
├───────────┼────────────────┤
│ Torgersen │           39.1 │
│ Torgersen │           39.5 │
│ Torgersen │           40.3 │
│ Torgersen │            nan │
│ Torgersen │           36.7 │
└───────────┴────────────────┘

Projection by zero-indexed column position

>>> t.select(0, 4).head()
┏━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┓
┃ species ┃ flipper_length_mm ┃
┡━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━┩
│ string  │ int64             │
├─────────┼───────────────────┤
│ Adelie  │               181 │
│ Adelie  │               186 │
│ Adelie  │               195 │
│ Adelie  │              NULL │
│ Adelie  │               193 │
└─────────┴───────────────────┘

Projection with renaming and compute in one call

>>> t.select(next_year=t.year + 1).head()
┏━━━━━━━━━━━┓
┃ next_year ┃
┡━━━━━━━━━━━┩
│ int64     │
├───────────┤
│      2008 │
│      2008 │
│      2008 │
│      2008 │
│      2008 │
└───────────┘

Projection with aggregation expressions

>>> t.select("island", bill_mean=t.bill_length_mm.mean()).head()
┏━━━━━━━━━━━┳━━━━━━━━━━━┓
┃ island    ┃ bill_mean ┃
┡━━━━━━━━━━━╇━━━━━━━━━━━┩
│ string    │ float64   │
├───────────┼───────────┤
│ Torgersen │  43.92193 │
│ Torgersen │  43.92193 │
│ Torgersen │  43.92193 │
│ Torgersen │  43.92193 │
│ Torgersen │  43.92193 │
└───────────┴───────────┘

Projection with a selector

>>> import ibis.selectors as s
>>> t.select(s.numeric() & ~s.c("year")).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 │
│            nan │           nan │              NULL │        NULL │
│           36.7 │          19.3 │               193 │        3450 │
└────────────────┴───────────────┴───────────────────┴─────────────┘

Projection + aggregation across multiple columns

>>> from ibis import _
>>> t.select(s.across(s.numeric() & ~s.c("year"), _.mean())).head()
┏━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┓
┃ bill_length_mm ┃ bill_depth_mm ┃ flipper_length_mm ┃ body_mass_g ┃
┡━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━┩
│ float64        │ float64       │ float64           │ float64     │
├────────────────┼───────────────┼───────────────────┼─────────────┤
│       43.92193 │      17.15117 │        200.915205 │ 4201.754386 │
│       43.92193 │      17.15117 │        200.915205 │ 4201.754386 │
│       43.92193 │      17.15117 │        200.915205 │ 4201.754386 │
│       43.92193 │      17.15117 │        200.915205 │ 4201.754386 │
│       43.92193 │      17.15117 │        200.915205 │ 4201.754386 │
└────────────────┴───────────────┴───────────────────┴─────────────┘
Source code in ibis/expr/types/relations.py
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
def select(
    self,
    *exprs: ir.Value | str | Iterable[ir.Value | str],
    **named_exprs: ir.Value | str,
) -> Table:
    """Compute a new table expression using `exprs` and `named_exprs`.

    Passing an aggregate function to this method will broadcast the
    aggregate's value over the number of rows in the table and
    automatically constructs a window function expression. See the examples
    section for more details.

    For backwards compatibility the keyword argument `exprs` is reserved
    and cannot be used to name an expression. This behavior will be removed
    in v4.

    Parameters
    ----------
    exprs
        Column expression, string, or list of column expressions and
        strings.
    named_exprs
        Column expressions

    Returns
    -------
    Table
        Table expression

    Examples
    --------
    >>> import ibis
    >>> 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 │            nan │           nan │              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 │ … │
    │ …       │ …         │              … │             … │                 … │ … │
    └─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘

    Simple projection

    >>> t.select("island", "bill_length_mm").head()
    ┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┓
    ┃ island    ┃ bill_length_mm ┃
    ┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━━┩
    │ string    │ float64        │
    ├───────────┼────────────────┤
    │ Torgersen │           39.1 │
    │ Torgersen │           39.5 │
    │ Torgersen │           40.3 │
    │ Torgersen │            nan │
    │ Torgersen │           36.7 │
    └───────────┴────────────────┘

    Projection by zero-indexed column position

    >>> t.select(0, 4).head()
    ┏━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┓
    ┃ species ┃ flipper_length_mm ┃
    ┡━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━┩
    │ string  │ int64             │
    ├─────────┼───────────────────┤
    │ Adelie  │               181 │
    │ Adelie  │               186 │
    │ Adelie  │               195 │
    │ Adelie  │              NULL │
    │ Adelie  │               193 │
    └─────────┴───────────────────┘

    Projection with renaming and compute in one call

    >>> t.select(next_year=t.year + 1).head()
    ┏━━━━━━━━━━━┓
    ┃ next_year ┃
    ┡━━━━━━━━━━━┩
    │ int64     │
    ├───────────┤
    │      2008 │
    │      2008 │
    │      2008 │
    │      2008 │
    │      2008 │
    └───────────┘

    Projection with aggregation expressions

    >>> t.select("island", bill_mean=t.bill_length_mm.mean()).head()
    ┏━━━━━━━━━━━┳━━━━━━━━━━━┓
    ┃ island    ┃ bill_mean ┃
    ┡━━━━━━━━━━━╇━━━━━━━━━━━┩
    │ string    │ float64   │
    ├───────────┼───────────┤
    │ Torgersen │  43.92193 │
    │ Torgersen │  43.92193 │
    │ Torgersen │  43.92193 │
    │ Torgersen │  43.92193 │
    │ Torgersen │  43.92193 │
    └───────────┴───────────┘

    Projection with a selector

    >>> import ibis.selectors as s
    >>> t.select(s.numeric() & ~s.c("year")).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 │
    │            nan │           nan │              NULL │        NULL │
    │           36.7 │          19.3 │               193 │        3450 │
    └────────────────┴───────────────┴───────────────────┴─────────────┘

    Projection + aggregation across multiple columns

    >>> from ibis import _
    >>> t.select(s.across(s.numeric() & ~s.c("year"), _.mean())).head()
    ┏━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┓
    ┃ bill_length_mm ┃ bill_depth_mm ┃ flipper_length_mm ┃ body_mass_g ┃
    ┡━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━┩
    │ float64        │ float64       │ float64           │ float64     │
    ├────────────────┼───────────────┼───────────────────┼─────────────┤
    │       43.92193 │      17.15117 │        200.915205 │ 4201.754386 │
    │       43.92193 │      17.15117 │        200.915205 │ 4201.754386 │
    │       43.92193 │      17.15117 │        200.915205 │ 4201.754386 │
    │       43.92193 │      17.15117 │        200.915205 │ 4201.754386 │
    │       43.92193 │      17.15117 │        200.915205 │ 4201.754386 │
    └────────────────┴───────────────┴───────────────────┴─────────────┘
    """
    import ibis.expr.analysis as an
    from ibis.selectors import Selector

    exprs = list(
        itertools.chain(
            itertools.chain.from_iterable(
                util.promote_list(e.expand(self) if isinstance(e, Selector) else e)
                for e in exprs
            ),
            (
                self._ensure_expr(expr).name(name)
                for name, expr in named_exprs.items()
            ),
        )
    )

    if not exprs:
        raise com.IbisTypeError(
            "You must select at least one column for a valid projection"
        )

    op = an.Projector(self, exprs).get_result()

    return op.to_expr()

sql(query, dialect=None)

Run a SQL query against a table expression.

Parameters:

Name Type Description Default
query str

Query string

required
dialect str | None

Optional string indicating the dialect of query. Defaults to the backend's native dialect.

None

Returns:

Type Description
Table

An opaque table expression

Examples:

>>> import ibis
>>> from ibis import _
>>> ibis.options.interactive = True
>>> t = ibis.examples.penguins.fetch(table_name="penguins")
>>> expr = t.sql(
...     """
...     SELECT island, mean(bill_length_mm) AS avg_bill_length
...     FROM penguins
...     GROUP BY 1
...     ORDER BY 2 DESC
...     """
... )
>>> expr
┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┓
┃ island    ┃ avg_bill_length ┃
┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━┩
│ string    │ float64         │
├───────────┼─────────────────┤
│ Biscoe    │       45.257485 │
│ Dream     │       44.167742 │
│ Torgersen │       38.950980 │
└───────────┴─────────────────┘

Mix and match ibis expressions with SQL queries

>>> t = ibis.examples.penguins.fetch(table_name="penguins")
>>> expr = t.sql(
...     """
...     SELECT island, mean(bill_length_mm) AS avg_bill_length
...     FROM penguins
...     GROUP BY 1
...     ORDER BY 2 DESC
...     """
... )
>>> expr = expr.mutate(
...     island=_.island.lower(),
...     avg_bill_length=_.avg_bill_length.round(1),
... )
>>> expr
┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┓
┃ island    ┃ avg_bill_length ┃
┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━┩
│ string    │ float64         │
├───────────┼─────────────────┤
│ biscoe    │            45.3 │
│ dream     │            44.2 │
│ torgersen │            39.0 │
└───────────┴─────────────────┘

Because ibis expressions aren't named, they aren't visible to subsequent .sql calls. Use the alias method to assign a name to an expression.

>>> expr.alias("b").sql("SELECT * FROM b WHERE avg_bill_length > 40")
┏━━━━━━━━┳━━━━━━━━━━━━━━━━━┓
┃ island ┃ avg_bill_length ┃
┡━━━━━━━━╇━━━━━━━━━━━━━━━━━┩
│ string │ float64         │
├────────┼─────────────────┤
│ biscoe │            45.3 │
│ dream  │            44.2 │
└────────┴─────────────────┘
See Also

Table.alias

Source code in ibis/expr/types/relations.py
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
def sql(self, query: str, dialect: str | None = None) -> ir.Table:
    '''Run a SQL query against a table expression.

    Parameters
    ----------
    query
        Query string
    dialect
        Optional string indicating the dialect of `query`. Defaults to the
        backend's native dialect.

    Returns
    -------
    Table
        An opaque table expression

    Examples
    --------
    >>> import ibis
    >>> from ibis import _
    >>> ibis.options.interactive = True
    >>> t = ibis.examples.penguins.fetch(table_name="penguins")
    >>> expr = t.sql(
    ...     """
    ...     SELECT island, mean(bill_length_mm) AS avg_bill_length
    ...     FROM penguins
    ...     GROUP BY 1
    ...     ORDER BY 2 DESC
    ...     """
    ... )
    >>> expr
    ┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┓
    ┃ island    ┃ avg_bill_length ┃
    ┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━┩
    │ string    │ float64         │
    ├───────────┼─────────────────┤
    │ Biscoe    │       45.257485 │
    │ Dream     │       44.167742 │
    │ Torgersen │       38.950980 │
    └───────────┴─────────────────┘

    Mix and match ibis expressions with SQL queries

    >>> t = ibis.examples.penguins.fetch(table_name="penguins")
    >>> expr = t.sql(
    ...     """
    ...     SELECT island, mean(bill_length_mm) AS avg_bill_length
    ...     FROM penguins
    ...     GROUP BY 1
    ...     ORDER BY 2 DESC
    ...     """
    ... )
    >>> expr = expr.mutate(
    ...     island=_.island.lower(),
    ...     avg_bill_length=_.avg_bill_length.round(1),
    ... )
    >>> expr
    ┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┓
    ┃ island    ┃ avg_bill_length ┃
    ┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━┩
    │ string    │ float64         │
    ├───────────┼─────────────────┤
    │ biscoe    │            45.3 │
    │ dream     │            44.2 │
    │ torgersen │            39.0 │
    └───────────┴─────────────────┘

    Because ibis expressions aren't named, they aren't visible to
    subsequent `.sql` calls. Use the [`alias`][ibis.expr.types.relations.Table.alias] method
    to assign a name to an expression.

    >>> expr.alias("b").sql("SELECT * FROM b WHERE avg_bill_length > 40")
    ┏━━━━━━━━┳━━━━━━━━━━━━━━━━━┓
    ┃ island ┃ avg_bill_length ┃
    ┡━━━━━━━━╇━━━━━━━━━━━━━━━━━┩
    │ string │ float64         │
    ├────────┼─────────────────┤
    │ biscoe │            45.3 │
    │ dream  │            44.2 │
    └────────┴─────────────────┘

    See Also
    --------
    [`Table.alias`][ibis.expr.types.relations.Table.alias]
    '''

    # only transpile if dialect was passed
    if dialect is not None:
        backend = self._find_backend()
        query = backend._transpile_sql(query, dialect=dialect)
    op = ops.SQLStringView(child=self, name=next(_ALIASES), query=query)
    return op.to_expr()

to_array()

View a single column table as an array.

Returns:

Type Description
Value

A single column view of a table

Source code in ibis/expr/types/relations.py
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
def to_array(self) -> ir.Column:
    """View a single column table as an array.

    Returns
    -------
    Value
        A single column view of a table
    """
    schema = self.schema()
    if len(schema) != 1:
        raise com.ExpressionError(
            'Table must have exactly one column when viewed as array'
        )

    return ops.TableArrayView(self).to_expr()

to_pandas(**kwargs)

Convert a table expression to a pandas DataFrame.

Parameters:

Name Type Description Default
kwargs

Same as keyword arguments to execute

{}
Source code in ibis/expr/types/relations.py
2782
2783
2784
2785
2786
2787
2788
2789
2790
def to_pandas(self, **kwargs) -> pd.DataFrame:
    """Convert a table expression to a pandas DataFrame.

    Parameters
    ----------
    kwargs
        Same as keyword arguments to [`execute`][ibis.expr.types.core.Expr.execute]
    """
    return self.execute(**kwargs)

try_cast(schema)

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:

Name Type Description Default
schema SupportsSchema

Mapping, schema or iterable of pairs to use for casting

required

Returns:

Type Description
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 │     nan │
└───────┴─────────┘
Source code in ibis/expr/types/relations.py
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
def try_cast(self, schema: SupportsSchema) -> 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 │     nan │
    └───────┴─────────┘
    """
    return self._cast(schema, cast_method="try_cast")

union(table, *rest, distinct=False)

Compute the set union of multiple table expressions.

The input tables must have identical schemas.

Parameters:

Name Type Description Default
table Table

A table expression

required
*rest Table

Additional table expressions

()
distinct bool

Only return distinct rows

False

Returns:

Type Description
Table

A new table containing the union of all input tables.

See Also

ibis.union

Examples:

>>> import ibis
>>> ibis.options.interactive = True
>>> t1 = ibis.memtable({"a": [1, 2]})
>>> t1
┏━━━━━━━┓
┃ a     ┃
┡━━━━━━━┩
│ int64 │
├───────┤
│     1 │
│     2 │
└───────┘
>>> t2 = ibis.memtable({"a": [2, 3]})
>>> t2
┏━━━━━━━┓
┃ a     ┃
┡━━━━━━━┩
│ int64 │
├───────┤
│     2 │
│     3 │
└───────┘
>>> t1.union(t2)  # union all by default
┏━━━━━━━┓
┃ a     ┃
┡━━━━━━━┩
│ int64 │
├───────┤
│     1 │
│     2 │
│     2 │
│     3 │
└───────┘
>>> t1.union(t2, distinct=True).order_by("a")
┏━━━━━━━┓
┃ a     ┃
┡━━━━━━━┩
│ int64 │
├───────┤
│     1 │
│     2 │
│     3 │
└───────┘
Source code in ibis/expr/types/relations.py
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
def union(self, table: Table, *rest: Table, distinct: bool = False) -> Table:
    """Compute the set union of multiple table expressions.

    The input tables must have identical schemas.

    Parameters
    ----------
    table
        A table expression
    *rest
        Additional table expressions
    distinct
        Only return distinct rows

    Returns
    -------
    Table
        A new table containing the union of all input tables.

    See Also
    --------
    [`ibis.union`][ibis.union]

    Examples
    --------
    >>> import ibis
    >>> ibis.options.interactive = True
    >>> t1 = ibis.memtable({"a": [1, 2]})
    >>> t1
    ┏━━━━━━━┓
    ┃ a     ┃
    ┡━━━━━━━┩
    │ int64 │
    ├───────┤
    │     1 │
    │     2 │
    └───────┘
    >>> t2 = ibis.memtable({"a": [2, 3]})
    >>> t2
    ┏━━━━━━━┓
    ┃ a     ┃
    ┡━━━━━━━┩
    │ int64 │
    ├───────┤
    │     2 │
    │     3 │
    └───────┘
    >>> t1.union(t2)  # union all by default
    ┏━━━━━━━┓
    ┃ a     ┃
    ┡━━━━━━━┩
    │ int64 │
    ├───────┤
    │     1 │
    │     2 │
    │     2 │
    │     3 │
    └───────┘
    >>> t1.union(t2, distinct=True).order_by("a")
    ┏━━━━━━━┓
    ┃ a     ┃
    ┡━━━━━━━┩
    │ int64 │
    ├───────┤
    │     1 │
    │     2 │
    │     3 │
    └───────┘
    """
    node = ops.Union(self, table, distinct=distinct)
    for table in rest:
        node = ops.Union(node, table, distinct=distinct)
    return node.to_expr().select(self.columns)

unpack(*columns)

Project the struct fields of each of columns into self.

Existing fields are retained in the projection.

Parameters:

Name Type Description Default
columns str

String column names to project into self.

()

Returns:

Type Description
Table

The child table with struct fields of each of columns projected.

Examples:

>>> import ibis
>>> ibis.options.interactive = True
>>> lines = '''
...     {"name": "a", "pos": {"lat": 10.1, "lon": 30.3}}
...     {"name": "b", "pos": {"lat": 10.2, "lon": 30.2}}
...     {"name": "c", "pos": {"lat": 10.3, "lon": 30.1}}
... '''
>>> with open("/tmp/lines.json", "w") as f:
...     _ = f.write(lines)
>>> t = ibis.read_json("/tmp/lines.json")
>>> t
┏━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ name   ┃ pos                                ┃
┡━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ string │ struct<lat: float64, lon: float64> │
├────────┼────────────────────────────────────┤
│ a      │ {'lat': 10.1, 'lon': 30.3}         │
│ b      │ {'lat': 10.2, 'lon': 30.2}         │
│ c      │ {'lat': 10.3, 'lon': 30.1}         │
└────────┴────────────────────────────────────┘
>>> t.unpack("pos")
┏━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┓
┃ name   ┃ lat     ┃ lon     ┃
┡━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━┩
│ string │ float64 │ float64 │
├────────┼─────────┼─────────┤
│ a      │    10.1 │    30.3 │
│ b      │    10.2 │    30.2 │
│ c      │    10.3 │    30.1 │
└────────┴─────────┴─────────┘
See Also

StructValue.lift

Source code in ibis/expr/types/relations.py
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
def unpack(self, *columns: str) -> Table:
    """Project the struct fields of each of `columns` into `self`.

    Existing fields are retained in the projection.

    Parameters
    ----------
    columns
        String column names to project into `self`.

    Returns
    -------
    Table
        The child table with struct fields of each of `columns` projected.

    Examples
    --------
    >>> import ibis
    >>> ibis.options.interactive = True
    >>> lines = '''
    ...     {"name": "a", "pos": {"lat": 10.1, "lon": 30.3}}
    ...     {"name": "b", "pos": {"lat": 10.2, "lon": 30.2}}
    ...     {"name": "c", "pos": {"lat": 10.3, "lon": 30.1}}
    ... '''
    >>> with open("/tmp/lines.json", "w") as f:
    ...     _ = f.write(lines)
    >>> t = ibis.read_json("/tmp/lines.json")
    >>> t
    ┏━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
    ┃ name   ┃ pos                                ┃
    ┡━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
    │ string │ struct<lat: float64, lon: float64> │
    ├────────┼────────────────────────────────────┤
    │ a      │ {'lat': 10.1, 'lon': 30.3}         │
    │ b      │ {'lat': 10.2, 'lon': 30.2}         │
    │ c      │ {'lat': 10.3, 'lon': 30.1}         │
    └────────┴────────────────────────────────────┘
    >>> t.unpack("pos")
    ┏━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┓
    ┃ name   ┃ lat     ┃ lon     ┃
    ┡━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━┩
    │ string │ float64 │ float64 │
    ├────────┼─────────┼─────────┤
    │ a      │    10.1 │    30.3 │
    │ b      │    10.2 │    30.2 │
    │ c      │    10.3 │    30.1 │
    └────────┴─────────┴─────────┘

    See Also
    --------
    [`StructValue.lift`][ibis.expr.types.structs.StructValue.lift]
    """
    columns_to_unpack = frozenset(columns)
    result_columns = []
    for column in self.columns:
        if column in columns_to_unpack:
            expr = self[column]
            result_columns.extend(expr[field] for field in expr.names)
        else:
            result_columns.append(column)
    return self[result_columns]

view()

Create a new table expression distinct from the current one.

Use this API for any self-referencing operations like a self-join.

Returns:

Type Description
Table

Table expression

Source code in ibis/expr/types/relations.py
768
769
770
771
772
773
774
775
776
777
778
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.

    Returns
    -------
    Table
        Table expression
    """
    return ops.SelfReference(self).to_expr()

GroupedTable

An intermediate table expression to hold grouping information.

Source code in ibis/expr/types/groupby.py
 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
class GroupedTable:
    """An intermediate table expression to hold grouping information."""

    def __init__(
        self, table, by, having=None, order_by=None, window=None, **expressions
    ):
        self.table = table
        self.by = list(
            itertools.chain(
                itertools.chain.from_iterable(
                    _get_group_by_key(table, v) for v in util.promote_list(by)
                ),
                (
                    expr.name(k)
                    for k, v in expressions.items()
                    for expr in _get_group_by_key(table, v)
                ),
            )
        )

        if not self.by:
            raise com.IbisInputError("The grouping keys list is empty")

        self._order_by = order_by or []
        self._having = having or []
        self._window = window

    def __getitem__(self, args):
        # Shortcut for projection with window functions
        return self.select(*args)

    def __getattr__(self, attr):
        if hasattr(self.table, attr):
            return self._column_wrapper(attr)

        raise AttributeError("GroupBy has no attribute %r" % attr)

    def _column_wrapper(self, attr):
        col = self.table[attr]
        if isinstance(col, ir.NumericValue):
            return GroupedNumbers(col, self)
        else:
            return GroupedArray(col, self)

    def aggregate(self, metrics=None, **kwds) -> ir.Table:
        """Compute aggregates over a group by."""
        return self.table.aggregate(metrics, by=self.by, having=self._having, **kwds)

    agg = aggregate

    def having(self, expr: ir.BooleanScalar) -> GroupedTable:
        """Add a post-aggregation result filter `expr`.

        !!! warning "Expressions like `x is None` return `bool` and **will not** generate a SQL comparison to `NULL`"

        Parameters
        ----------
        expr
            An expression that filters based on an aggregate value.

        Returns
        -------
        GroupedTable
            A grouped table expression
        """
        return self.__class__(
            self.table,
            self.by,
            having=self._having + util.promote_list(expr),
            order_by=self._order_by,
            window=self._window,
        )

    def order_by(self, expr: ir.Value | Iterable[ir.Value]) -> GroupedTable:
        """Sort a grouped table expression by `expr`.

        Notes
        -----
        This API call is ignored in aggregations.

        Parameters
        ----------
        expr
            Expressions to order the results by

        Returns
        -------
        GroupedTable
            A sorted grouped GroupedTable
        """
        return self.__class__(
            self.table,
            self.by,
            having=self._having,
            order_by=self._order_by + util.promote_list(expr),
            window=self._window,
        )

    def mutate(
        self, *exprs: ir.Value | Sequence[ir.Value], **kwexprs: ir.Value
    ) -> ir.Table:
        """Return a table projection with window functions applied.

        Any arguments can be functions.

        Parameters
        ----------
        exprs
            List of expressions
        kwexprs
            Expressions

        Examples
        --------
        >>> import ibis
        >>> t = ibis.table([
        ...     ('foo', 'string'),
        ...     ('bar', 'string'),
        ...     ('baz', 'double'),
        ... ], name='t')
        >>> t
        UnboundTable: t
          foo string
          bar string
          baz float64
        >>> expr = (t.group_by('foo')
        ...          .order_by(ibis.desc('bar'))
        ...          .mutate(qux=lambda x: x.baz.lag(), qux2=t.baz.lead()))
        >>> print(expr)
        r0 := UnboundTable: t
          foo string
          bar string
          baz float64
        Selection[r0]
          selections:
            r0
            qux:  WindowFunction(...)
            qux2: WindowFunction(...)

        Returns
        -------
        Table
            A table expression with window functions applied
        """

        exprs = self._selectables(*exprs, **kwexprs)
        return self.table.mutate(exprs)

    def select(self, *exprs, **kwexprs) -> ir.Table:
        """Project new columns out of the grouped table.

        See Also
        --------
        [`GroupedTable.mutate`][ibis.expr.types.groupby.GroupedTable.mutate]
        """
        exprs = self._selectables(*exprs, **kwexprs)
        return self.table.select(exprs)

    def _selectables(self, *exprs, **kwexprs):
        """Project new columns out of the grouped table.

        See Also
        --------
        [`GroupedTable.mutate`][ibis.expr.types.groupby.GroupedTable.mutate]
        """
        table = self.table
        default_frame = self._get_window()
        return [
            an.windowize_function(e2, frame=default_frame)
            for expr in exprs
            for e1 in util.promote_list(expr)
            for e2 in util.promote_list(table._ensure_expr(e1))
        ] + [
            an.windowize_function(e, frame=default_frame).name(k)
            for k, expr in kwexprs.items()
            for e in util.promote_list(table._ensure_expr(expr))
        ]

    projection = select

    def _get_window(self):
        if self._window is None:
            return ops.RowsWindowFrame(
                table=self.table,
                group_by=self.by,
                order_by=bind_expr(self.table, self._order_by),
            )
        else:
            return self._window.copy(
                groupy_by=bind_expr(self.table, self._window.group_by + self.by),
                order_by=bind_expr(self.table, self._window.order_by + self._order_by),
            )

    def over(
        self,
        window=None,
        *,
        rows=None,
        range=None,
        group_by=None,
        order_by=None,
    ) -> GroupedTable:
        """Apply a window over the input expressions.

        Parameters
        ----------
        window
            Window to add to the input
        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
        -------
        GroupedTable
            A new grouped table expression
        """
        if window is None:
            window = ibis.window(
                rows=rows,
                range=range,
                group_by=group_by,
                order_by=order_by,
            )

        return self.__class__(
            self.table,
            self.by,
            having=self._having,
            order_by=self._order_by,
            window=window,
        )

    def count(self) -> ir.Table:
        """Computing the number of rows per group.

        Returns
        -------
        Table
            The aggregated table
        """
        metric = self.table.count()
        return self.table.aggregate([metric], by=self.by, having=self._having)

    size = count

Functions

aggregate(metrics=None, **kwds)

Compute aggregates over a group by.

Source code in ibis/expr/types/groupby.py
108
109
110
def aggregate(self, metrics=None, **kwds) -> ir.Table:
    """Compute aggregates over a group by."""
    return self.table.aggregate(metrics, by=self.by, having=self._having, **kwds)

count()

Computing the number of rows per group.

Returns:

Type Description
Table

The aggregated table

Source code in ibis/expr/types/groupby.py
302
303
304
305
306
307
308
309
310
311
def count(self) -> ir.Table:
    """Computing the number of rows per group.

    Returns
    -------
    Table
        The aggregated table
    """
    metric = self.table.count()
    return self.table.aggregate([metric], by=self.by, having=self._having)

having(expr)

Add a post-aggregation result filter expr.

Expressions like x is None return bool and will not generate a SQL comparison to NULL

Parameters:

Name Type Description Default
expr ir.BooleanScalar

An expression that filters based on an aggregate value.

required

Returns:

Type Description
GroupedTable

A grouped table expression

Source code in ibis/expr/types/groupby.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def having(self, expr: ir.BooleanScalar) -> GroupedTable:
    """Add a post-aggregation result filter `expr`.

    !!! warning "Expressions like `x is None` return `bool` and **will not** generate a SQL comparison to `NULL`"

    Parameters
    ----------
    expr
        An expression that filters based on an aggregate value.

    Returns
    -------
    GroupedTable
        A grouped table expression
    """
    return self.__class__(
        self.table,
        self.by,
        having=self._having + util.promote_list(expr),
        order_by=self._order_by,
        window=self._window,
    )

mutate(*exprs, **kwexprs)

Return a table projection with window functions applied.

Any arguments can be functions.

Parameters:

Name Type Description Default
exprs ir.Value | Sequence[ir.Value]

List of expressions

()
kwexprs ir.Value

Expressions

{}

Examples:

>>> import ibis
>>> t = ibis.table([
...     ('foo', 'string'),
...     ('bar', 'string'),
...     ('baz', 'double'),
... ], name='t')
>>> t
UnboundTable: t
  foo string
  bar string
  baz float64
>>> expr = (t.group_by('foo')
...          .order_by(ibis.desc('bar'))
...          .mutate(qux=lambda x: x.baz.lag(), qux2=t.baz.lead()))
>>> print(expr)
r0 := UnboundTable: t
  foo string
  bar string
  baz float64
Selection[r0]
  selections:
    r0
    qux:  WindowFunction(...)
    qux2: WindowFunction(...)

Returns:

Type Description
Table

A table expression with window functions applied

Source code in ibis/expr/types/groupby.py
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
def mutate(
    self, *exprs: ir.Value | Sequence[ir.Value], **kwexprs: ir.Value
) -> ir.Table:
    """Return a table projection with window functions applied.

    Any arguments can be functions.

    Parameters
    ----------
    exprs
        List of expressions
    kwexprs
        Expressions

    Examples
    --------
    >>> import ibis
    >>> t = ibis.table([
    ...     ('foo', 'string'),
    ...     ('bar', 'string'),
    ...     ('baz', 'double'),
    ... ], name='t')
    >>> t
    UnboundTable: t
      foo string
      bar string
      baz float64
    >>> expr = (t.group_by('foo')
    ...          .order_by(ibis.desc('bar'))
    ...          .mutate(qux=lambda x: x.baz.lag(), qux2=t.baz.lead()))
    >>> print(expr)
    r0 := UnboundTable: t
      foo string
      bar string
      baz float64
    Selection[r0]
      selections:
        r0
        qux:  WindowFunction(...)
        qux2: WindowFunction(...)

    Returns
    -------
    Table
        A table expression with window functions applied
    """

    exprs = self._selectables(*exprs, **kwexprs)
    return self.table.mutate(exprs)

order_by(expr)

Sort a grouped table expression by expr.

Notes

This API call is ignored in aggregations.

Parameters:

Name Type Description Default
expr ir.Value | Iterable[ir.Value]

Expressions to order the results by

required

Returns:

Type Description
GroupedTable

A sorted grouped GroupedTable

Source code in ibis/expr/types/groupby.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
def order_by(self, expr: ir.Value | Iterable[ir.Value]) -> GroupedTable:
    """Sort a grouped table expression by `expr`.

    Notes
    -----
    This API call is ignored in aggregations.

    Parameters
    ----------
    expr
        Expressions to order the results by

    Returns
    -------
    GroupedTable
        A sorted grouped GroupedTable
    """
    return self.__class__(
        self.table,
        self.by,
        having=self._having,
        order_by=self._order_by + util.promote_list(expr),
        window=self._window,
    )

over(window=None, *, rows=None, range=None, group_by=None, order_by=None)

Apply a window over the input expressions.

Parameters:

Name Type Description Default
window

Window to add to the input

None
rows

Whether to use the ROWS window clause

None
range

Whether to use the RANGE window clause

None
group_by

Grouping key

None
order_by

Ordering key

None

Returns:

Type Description
GroupedTable

A new grouped table expression

Source code in ibis/expr/types/groupby.py
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
def over(
    self,
    window=None,
    *,
    rows=None,
    range=None,
    group_by=None,
    order_by=None,
) -> GroupedTable:
    """Apply a window over the input expressions.

    Parameters
    ----------
    window
        Window to add to the input
    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
    -------
    GroupedTable
        A new grouped table expression
    """
    if window is None:
        window = ibis.window(
            rows=rows,
            range=range,
            group_by=group_by,
            order_by=order_by,
        )

    return self.__class__(
        self.table,
        self.by,
        having=self._having,
        order_by=self._order_by,
        window=window,
    )

select(*exprs, **kwexprs)

Project new columns out of the grouped table.

See Also

GroupedTable.mutate

Source code in ibis/expr/types/groupby.py
212
213
214
215
216
217
218
219
220
def select(self, *exprs, **kwexprs) -> ir.Table:
    """Project new columns out of the grouped table.

    See Also
    --------
    [`GroupedTable.mutate`][ibis.expr.types.groupby.GroupedTable.mutate]
    """
    exprs = self._selectables(*exprs, **kwexprs)
    return self.table.select(exprs)

Last update: June 22, 2023