Skip to content

Table

A table is a two-dimensional collection of data. It can either be seen as a list of rows or as a list of columns.

To create a Table call the constructor or use one of the following static methods:

Method Description
from_csv_file Create a table from a CSV file.
from_json_file Create a table from a JSON file.
from_dict Create a table from a dictionary.
from_columns Create a table from a list of columns.
from_rows Create a table from a list of rows.

Note: When removing the last column of the table, the number_of_columns property will be set to 0.

Parameters:

Name Type Description Default
data Mapping[str, Sequence[Any]] | None

The data. If None, an empty table is created.

None

Raises:

Type Description
ColumnLengthMismatchError

If columns have different lengths.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table({"a": [1, 2, 3], "b": [4, 5, 6]})
Source code in src/safeds/data/tabular/containers/_table.py
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
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
class Table:
    """
    A table is a two-dimensional collection of data. It can either be seen as a list of rows or as a list of columns.

    To create a `Table` call the constructor or use one of the following static methods:

    | Method                                                                       | Description                            |
    | ---------------------------------------------------------------------------- | -------------------------------------- |
    | [from_csv_file][safeds.data.tabular.containers._table.Table.from_csv_file]   | Create a table from a CSV file.        |
    | [from_json_file][safeds.data.tabular.containers._table.Table.from_json_file] | Create a table from a JSON file.       |
    | [from_dict][safeds.data.tabular.containers._table.Table.from_dict]           | Create a table from a dictionary.      |
    | [from_columns][safeds.data.tabular.containers._table.Table.from_columns]     | Create a table from a list of columns. |
    | [from_rows][safeds.data.tabular.containers._table.Table.from_rows]           | Create a table from a list of rows.    |

    Note: When removing the last column of the table, the `number_of_columns` property will be set to 0.

    Parameters
    ----------
    data : Mapping[str, Sequence[Any]] | None
        The data. If None, an empty table is created.

    Raises
    ------
    ColumnLengthMismatchError
        If columns have different lengths.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table({"a": [1, 2, 3], "b": [4, 5, 6]})
    """

    # ------------------------------------------------------------------------------------------------------------------
    # Creation
    # ------------------------------------------------------------------------------------------------------------------

    @staticmethod
    def from_csv_file(path: str | Path) -> Table:
        """
        Read data from a CSV file into a table.

        Parameters
        ----------
        path : str | Path
            The path to the CSV file.

        Returns
        -------
        table : Table
            The table created from the CSV file.

        Raises
        ------
        FileNotFoundError
            If the specified file does not exist.
        WrongFileExtensionError
            If the file is not a csv file.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> Table.from_csv_file('./src/resources/from_csv_file.csv')
           a  b  c
        0  1  2  1
        1  0  0  7
        """
        import pandas as pd

        path = Path(path)
        if path.suffix != ".csv":
            raise WrongFileExtensionError(path, ".csv")
        if path.exists():
            with path.open() as f:
                if f.read().replace("\n", "") == "":
                    return Table()

            return Table._from_pandas_dataframe(pd.read_csv(path))
        else:
            raise FileNotFoundError(f'File "{path}" does not exist')

    @staticmethod
    def from_excel_file(path: str | Path) -> Table:
        """
        Read data from an Excel file into a table.

        Valid file extensions are `.xls`, '.xlsx', `.xlsm`, `.xlsb`, `.odf`, `.ods` and `.odt`.

        Parameters
        ----------
        path : str | Path
            The path to the Excel file.

        Returns
        -------
        table : Table
            The table created from the Excel file.

        Raises
        ------
        FileNotFoundError
            If the specified file does not exist.
        WrongFileExtensionError
            If the file is not an Excel file.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> Table.from_excel_file('./src/resources/from_excel_file.xlsx')
           a  b
        0  1  4
        1  2  5
        2  3  6
        """
        import pandas as pd

        path = Path(path)
        excel_extensions = [".xls", ".xlsx", ".xlsm", ".xlsb", ".odf", ".ods", ".odt"]
        if path.suffix not in excel_extensions:
            raise WrongFileExtensionError(path, excel_extensions)
        try:
            return Table._from_pandas_dataframe(
                pd.read_excel(path, engine="openpyxl", usecols=lambda colname: "Unnamed" not in colname),
            )
        except FileNotFoundError as exception:
            raise FileNotFoundError(f'File "{path}" does not exist') from exception

    @staticmethod
    def from_json_file(path: str | Path) -> Table:
        """
        Read data from a JSON file into a table.

        Parameters
        ----------
        path : str | Path
            The path to the JSON file.

        Returns
        -------
        table : Table
            The table created from the JSON file.

        Raises
        ------
        FileNotFoundError
            If the specified file does not exist.
        WrongFileExtensionError
            If the file is not a JSON file.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> Table.from_json_file('./src/resources/from_json_file.json')
           a  b
        0  1  4
        1  2  5
        2  3  6
        """
        import pandas as pd

        path = Path(path)
        if path.suffix != ".json":
            raise WrongFileExtensionError(path, ".json")
        if path.exists():
            with path.open() as f:
                if f.read().replace("\n", "") in ("", "{}"):
                    return Table()

            return Table._from_pandas_dataframe(pd.read_json(path))
        else:
            raise FileNotFoundError(f'File "{path}" does not exist')

    @staticmethod
    def from_dict(data: dict[str, list[Any]]) -> Table:
        """
        Create a table from a dictionary that maps column names to column values.

        Parameters
        ----------
        data : dict[str, list[Any]]
            The data.

        Returns
        -------
        table : Table
            The generated table.

        Raises
        ------
        ColumnLengthMismatchError
            If columns have different lengths.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> d = {'a': [1, 2], 'b': [3, 4]}
        >>> Table.from_dict(d)
           a  b
        0  1  3
        1  2  4
        """
        return Table(data)

    @staticmethod
    def from_columns(columns: list[Column]) -> Table:
        """
        Return a table created from a list of columns.

        Parameters
        ----------
        columns : list[Column]
            The columns to be combined. They need to have the same size.

        Returns
        -------
        table : Table
            The generated table.

        Raises
        ------
        ColumnLengthMismatchError
            If any of the column sizes does not match with the others.
        DuplicateColumnNameError
            If multiple columns have the same name.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Column, Table
        >>> col1 = Column("a", [1, 2, 3])
        >>> col2 = Column("b", [4, 5, 6])
        >>> Table.from_columns([col1, col2])
           a  b
        0  1  4
        1  2  5
        2  3  6
        """
        import pandas as pd
        from pandas import DataFrame

        dataframe: DataFrame = pd.DataFrame()
        column_names = []

        for column in columns:
            if column._data.size != columns[0]._data.size:
                raise ColumnLengthMismatchError(
                    "\n".join(f"{column.name}: {column._data.size}" for column in columns),
                )
            if column.name in column_names:
                raise DuplicateColumnNameError(column.name)
            column_names.append(column.name)
            dataframe[column.name] = column._data

        return Table._from_pandas_dataframe(dataframe)

    @staticmethod
    def from_rows(rows: list[Row]) -> Table:
        """
        Return a table created from a list of rows.

        Parameters
        ----------
        rows : list[Row]
            The rows to be combined. They need to have a matching schema.

        Returns
        -------
        table : Table
            The generated table.

        Raises
        ------
        UnknownColumnNameError
            If any of the row column names does not match with the first row.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Row, Table
        >>> row1 = Row({"a": 1, "b": 2})
        >>> row2 = Row({"a": 3, "b": 4})
        >>> Table.from_rows([row1, row2])
           a  b
        0  1  2
        1  3  4
        """
        import pandas as pd
        from pandas import DataFrame

        if len(rows) == 0:
            return Table._from_pandas_dataframe(pd.DataFrame())

        column_names_compare: list = list(rows[0].column_names)
        unknown_column_names = set()
        row_array: list[pd.DataFrame] = []

        for row in rows:
            unknown_column_names.update(set(column_names_compare) - set(row.column_names))
            row_array.append(row._data)
        if len(unknown_column_names) > 0:
            raise UnknownColumnNameError(list(unknown_column_names))

        dataframe: DataFrame = pd.concat(row_array, ignore_index=True)
        dataframe.columns = column_names_compare

        schema = Schema._merge_multiple_schemas([row.schema for row in rows])

        return Table._from_pandas_dataframe(dataframe, schema)

    @staticmethod
    def _from_pandas_dataframe(data: pd.DataFrame, schema: Schema | None = None) -> Table:
        """
        Create a table from a `pandas.DataFrame`.

        Parameters
        ----------
        data : pd.DataFrame
            The data.
        schema : Schema | None
            The schema. If None, the schema is inferred from the data.

        Returns
        -------
        table : Table
            The created table.

        Examples
        --------
        >>> import pandas as pd
        >>> from safeds.data.tabular.containers import Table
        >>> Table._from_pandas_dataframe(pd.DataFrame({"a": [1], "b": [2]}))
           a  b
        0  1  2
        """
        import pandas as pd

        data = data.reset_index(drop=True)

        result = object.__new__(Table)
        result._data = data

        if schema is None:
            # noinspection PyProtectedMember
            result._schema = Schema._from_pandas_dataframe(data)
        else:
            result._schema = schema
            if result._data.empty:
                result._data = pd.DataFrame(columns=schema.column_names)

        return result

    # ------------------------------------------------------------------------------------------------------------------
    # Dunder methods
    # ------------------------------------------------------------------------------------------------------------------

    def __init__(self, data: Mapping[str, Sequence[Any]] | None = None) -> None:
        """
        Create a table from a mapping of column names to their values.

        Parameters
        ----------
        data : Mapping[str, Sequence[Any]] | None
            The data. If None, an empty table is created.

        Raises
        ------
        ColumnLengthMismatchError
            If columns have different lengths.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> Table({"a": [1, 2, 3], "b": [4, 5, 6]})
           a  b
        0  1  4
        1  2  5
        2  3  6
        """
        import pandas as pd

        # Enable copy-on-write for pandas dataframes
        pd.options.mode.copy_on_write = True

        if data is None:
            data = {}

        # Validation
        expected_length: int | None = None
        for column_values in data.values():
            if expected_length is None:
                expected_length = len(column_values)
            elif len(column_values) != expected_length:
                raise ColumnLengthMismatchError(
                    "\n".join(f"{column_name}: {len(column_values)}" for column_name, column_values in data.items()),
                )

        # Implementation
        self._data: pd.DataFrame = pd.DataFrame(data)
        self._data = self._data.reset_index(drop=True)
        self._schema: Schema = Schema._from_pandas_dataframe(self._data)

    def __eq__(self, other: object) -> bool:
        """
        Compare two table instances.

        Returns
        -------
        'True' if contents are equal, 'False' otherwise.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Row, Table
        >>> row1 = Row({"a": 1, "b": 2})
        >>> row2 = Row({"a": 3, "b": 4})
        >>> row3 = Row({"a": 5, "b": 6})
        >>> table1 = Table.from_rows([row1, row2])
        >>> table2 = Table.from_rows([row1, row2])
        >>> table3 = Table.from_rows([row1, row3])
        >>> table1 == table2
        True
        >>> table1 == table3
        False
        """
        if not isinstance(other, Table):
            return NotImplemented
        if self is other:
            return True
        if self.number_of_columns == 0 and other.number_of_columns == 0:
            return True
        table1 = self.sort_columns()
        table2 = other.sort_columns()
        if table1.number_of_rows == 0 and table2.number_of_rows == 0:
            return table1.column_names == table2.column_names
        return table1._schema == table2._schema and table1._data.equals(table2._data)

    def __hash__(self) -> int:
        """
        Return a deterministic hash value for this table.

        Returns
        -------
        hash:
            The hash value.
        """
        return _structural_hash(self._schema, self.number_of_rows)

    def __repr__(self) -> str:
        r"""
        Display the table in only one line.

        Returns
        -------
        A string representation of the table in only one line.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
        >>> repr(table)
        '   a  b\n0  1  2\n1  3  4'
        """
        tmp = self._data.reset_index(drop=True)
        tmp.columns = self.column_names
        return tmp.__repr__()

    def __sizeof__(self) -> int:
        """
        Return the complete size of this object.

        Returns
        -------
        size:
            Size of this object in bytes.
        """
        return sys.getsizeof(self._data) + sys.getsizeof(self._schema)

    def __str__(self) -> str:
        tmp = self._data.reset_index(drop=True)
        tmp.columns = self.column_names
        return tmp.__str__()

    # ------------------------------------------------------------------------------------------------------------------
    # Properties
    # ------------------------------------------------------------------------------------------------------------------

    @property
    def column_names(self) -> list[str]:
        """
        Return a list of all column names in this table.

        Alias for self.schema.column_names -> list[str].

        Returns
        -------
        column_names : list[str]
            The list of the column names.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"col1": [1, 3], "col2": [2, 4]})
        >>> table.column_names
        ['col1', 'col2']
        """
        return self._schema.column_names

    @property
    def number_of_columns(self) -> int:
        """
        Return the number of columns.

        Returns
        -------
        number_of_columns : int
            The number of columns.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1], "b": [2]})
        >>> table.number_of_columns
        2
        """
        return self._data.shape[1]

    @property
    def number_of_rows(self) -> int:
        """
        Return the number of rows.

        Returns
        -------
        number_of_rows : int
            The number of rows.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1], "b": [2]})
        >>> table.number_of_rows
        1
        """
        return self._data.shape[0]

    @property
    def schema(self) -> Schema:
        """
        Return the schema of the table.

        Returns
        -------
        schema : Schema
            The schema.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Row, Table
        >>> row = Row({"a": 1, "b": 2.5, "c": "ff"})
        >>> table = Table.from_dict({"a": [1, 8], "b": [2.5, 9], "c": ["g", "g"]})
        >>> table.schema
        Schema({
            'a': Integer,
            'b': RealNumber,
            'c': String
        })
        >>> table.schema == row.schema
        True
        """
        return self._schema

    # ------------------------------------------------------------------------------------------------------------------
    # Getters
    # ------------------------------------------------------------------------------------------------------------------

    def get_column(self, column_name: str) -> Column:
        """
        Return a column with the data of the specified column.

        Parameters
        ----------
        column_name : str
            The name of the column.

        Returns
        -------
        column : Column
            The column.

        Raises
        ------
        UnknownColumnNameError
            If the specified target column name does not exist.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1], "b": [2]})
        >>> table.get_column("b")
        Column('b', [2])
        """
        if not self.has_column(column_name):
            similar_columns = self._get_similar_columns(column_name)
            raise UnknownColumnNameError([column_name], similar_columns)

        return Column._from_pandas_series(
            self._data[column_name],
            self.get_column_type(column_name),
        )

    def has_column(self, column_name: str) -> bool:
        """
        Return whether the table contains a given column.

        Alias for self.schema.hasColumn(column_name: str) -> bool.

        Parameters
        ----------
        column_name : str
            The name of the column.

        Returns
        -------
        contains : bool
            True if the column exists.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1], "b": [2]})
        >>> table.has_column("b")
        True
        >>> table.has_column("c")
        False
        """
        return self._schema.has_column(column_name)

    def get_column_type(self, column_name: str) -> ColumnType:
        """
        Return the type of the given column.

        Alias for self.schema.get_type_of_column(column_name: str) -> ColumnType.

        Parameters
        ----------
        column_name : str
            The name of the column to be queried.

        Returns
        -------
        type : ColumnType
            The type of the column.

        Raises
        ------
        UnknownColumnNameError
            If the specified target column name does not exist.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1], "b": [2.5]})
        >>> table.get_column_type("b")
        RealNumber
        """
        return self._schema.get_column_type(column_name)

    def get_row(self, index: int) -> Row:
        """
        Return the row at a specified index.

        Parameters
        ----------
        index : int
            The index.

        Returns
        -------
        row : Row
            The row of the table at the index.

        Raises
        ------
        IndexOutOfBoundsError
            If no row at the specified index exists in this table.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
        >>> table.get_row(0)
        Row({
            'a': 1,
            'b': 2
        })
        """
        if len(self._data.index) - 1 < index or index < 0:
            raise IndexOutOfBoundsError(index)

        return Row._from_pandas_dataframe(self._data.iloc[[index]], self._schema)

    def _get_similar_columns(self, column_name: str) -> list[str]:
        """
        Get all the column names in a Table that are similar to a given name.

        Parameters
        ----------
        column_name : str
            The name to compare the Table's column names to.

        Returns
        -------
        similar_columns: list[str]
            A list of all column names in the Table that are similar or equal to the given column name.
        """
        import Levenshtein

        similar_columns = []
        similarity = 0.6
        i = 0
        while i < len(self.column_names):
            if Levenshtein.jaro_winkler(self.column_names[i], column_name) >= similarity:
                similar_columns.append(self.column_names[i])
            i += 1
            if len(similar_columns) == 4 and similarity < 0.9:
                similarity += 0.1
                similar_columns = []
                i = 0

        return similar_columns

    # ------------------------------------------------------------------------------------------------------------------
    # Information
    # ------------------------------------------------------------------------------------------------------------------

    def summarize_statistics(self) -> Table:
        """
        Return a table with a number of statistical key values.

        The original table is not modified.

        Returns
        -------
        result : Table
            The table with statistics.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
        >>> table.summarize_statistics()
                      metrics                   a                   b
        0             maximum                   3                   4
        1             minimum                   1                   2
        2                mean                 2.0                 3.0
        3                mode              [1, 3]              [2, 4]
        4              median                 2.0                 3.0
        5                 sum                   4                   6
        6            variance                 2.0                 2.0
        7  standard deviation  1.4142135623730951  1.4142135623730951
        8              idness                 1.0                 1.0
        9           stability                 0.5                 0.5
        """
        import pandas as pd

        if self.number_of_columns == 0:
            return Table(
                {
                    "metrics": [
                        "maximum",
                        "minimum",
                        "mean",
                        "mode",
                        "median",
                        "sum",
                        "variance",
                        "standard deviation",
                        "idness",
                        "stability",
                    ],
                },
            )
        elif self.number_of_rows == 0:
            table = Table(
                {
                    "metrics": [
                        "maximum",
                        "minimum",
                        "mean",
                        "mode",
                        "median",
                        "sum",
                        "variance",
                        "standard deviation",
                        "idness",
                        "stability",
                    ],
                },
            )
            for name in self.column_names:
                table = table.add_column(Column(name, ["-", "-", "-", "-", "-", "-", "-", "-", "-", "-"]))
            return table

        columns = self.to_columns()
        result = pd.DataFrame()
        statistics = {}

        for column in columns:
            statistics = {
                "maximum": column.maximum,
                "minimum": column.minimum,
                "mean": column.mean,
                "mode": column.mode,
                "median": column.median,
                "sum": column.sum,
                "variance": column.variance,
                "standard deviation": column.standard_deviation,
                "idness": column.idness,
                "stability": column.stability,
            }
            values = []

            for function in statistics.values():
                try:
                    values.append(str(function()))
                except (NonNumericColumnError, ValueError):
                    values.append("-")

            result = pd.concat([result, pd.DataFrame(values)], axis=1)

        result = pd.concat([pd.DataFrame(list(statistics.keys())), result], axis=1)
        result.columns = ["metrics", *self.column_names]

        return Table._from_pandas_dataframe(result)

    # ------------------------------------------------------------------------------------------------------------------
    # Transformations
    # ------------------------------------------------------------------------------------------------------------------

    def _as_table(self: Table) -> Table:
        """
        Transform the table to an instance of the Table class.

        This method is meant as a way to "cast" instances of subclasses of `Table` to a proper `Table`, dropping any
        additional constraints that might have to hold in the subclass. Override accordingly in subclasses.

        Returns
        -------
        table: Table
            The table, as an instance of the Table class.
        """
        return self

    def add_column(self, column: Column) -> Table:
        """
        Return a new table with the provided column attached at the end.

        The original table is not modified.

        Returns
        -------
        result : Table
            The table with the column attached.

        Raises
        ------
        DuplicateColumnNameError
            If the new column already exists.
        ColumnSizeError
            If the size of the column does not match the number of rows.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
        >>> col = Column("c", ["d", "e"])
        >>> table.add_column(col)
           a  b  c
        0  1  2  d
        1  3  4  e
        """
        if self.has_column(column.name):
            raise DuplicateColumnNameError(column.name)

        if column.number_of_rows != self.number_of_rows and self.number_of_columns != 0:
            raise ColumnSizeError(str(self.number_of_rows), str(column._data.size))

        result = self._data.reset_index(drop=True)
        result.columns = self._schema.column_names
        result[column.name] = column._data
        return Table._from_pandas_dataframe(result)

    def add_columns(self, columns: list[Column] | Table) -> Table:
        """
        Return a new `Table` with multiple added columns.

        The original table is not modified.

        Parameters
        ----------
        columns : list[Column] or Table
            The columns to be added.

        Returns
        -------
        result: Table
            A new table combining the original table and the given columns.

        Raises
        ------
        DuplicateColumnNameError
            If at least one column name from the provided column list already exists in the table.
        ColumnSizeError
            If at least one of the column sizes from the provided column list does not match the table.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Column, Table
        >>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
        >>> col1 = Column("c", ["d", "e"])
        >>> col2 = Column("d", [3.5, 7.9])
        >>> table.add_columns([col1, col2])
           a  b  c    d
        0  1  2  d  3.5
        1  3  4  e  7.9
        """
        if isinstance(columns, Table):
            columns = columns.to_columns()
        result = self._data.reset_index(drop=True)
        result.columns = self._schema.column_names
        for column in columns:
            if column.name in result.columns:
                raise DuplicateColumnNameError(column.name)

            if column.number_of_rows != self.number_of_rows and self.number_of_columns != 0:
                raise ColumnSizeError(str(self.number_of_rows), str(column._data.size))

            result[column.name] = column._data
        return Table._from_pandas_dataframe(result)

    def add_row(self, row: Row) -> Table:
        """
        Return a new `Table` with an added Row attached.

        If the table happens to be empty beforehand, respective columns will be added automatically.

        The order of columns of the new row will be adjusted to the order of columns in the table.
        The new table will contain the merged schema.

        The original table is not modified.

        Parameters
        ----------
        row : Row
            The row to be added.

        Returns
        -------
        table : Table
            A new table with the added row at the end.

        Raises
        ------
        UnknownColumnNameError
            If the row has different column names than the table.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Row, Table
        >>> table = Table.from_dict({"a": [1], "b": [2]})
        >>> row = Row.from_dict({"a": 3, "b": 4})
        >>> table.add_row(row)
           a  b
        0  1  2
        1  3  4
        """
        import numpy as np
        import pandas as pd

        int_columns = []

        if self.number_of_columns == 0:
            return Table.from_rows([row])
        if len(set(self.column_names) - set(row.column_names)) > 0:
            raise UnknownColumnNameError(
                sorted(
                    set(self.column_names) - set(row.column_names),
                    key={val: ix for ix, val in enumerate(self.column_names)}.__getitem__,
                ),
            )

        if self.number_of_rows == 0:
            int_columns = list(filter(lambda name: isinstance(row[name], int | np.int64 | np.int32), row.column_names))

        new_df = pd.concat([self._data, row._data]).infer_objects()
        new_df.columns = self.column_names
        schema = Schema._merge_multiple_schemas([self.schema, row.schema])
        result = Table._from_pandas_dataframe(new_df, schema)

        for column in int_columns:
            result = result.replace_column(column, [result.get_column(column).transform(lambda it: int(it))])

        return result

    def add_rows(self, rows: list[Row] | Table) -> Table:
        """
        Return a new `Table` with multiple added Rows attached.

        The order of columns of the new rows will be adjusted to the order of columns in the table.
        The new table will contain the merged schema.

        The original table is not modified.

        Parameters
        ----------
        rows : list[Row] or Table
            The rows to be added.

        Returns
        -------
        result : Table
            A new table which combines the original table and the given rows.

        Raises
        ------
        UnknownColumnNameError
            If at least one of the rows have different column names than the table.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Row, Table
        >>> table = Table.from_dict({"a": [1], "b": [2]})
        >>> row1 = Row.from_dict({"a": 3, "b": 4})
        >>> row2 = Row.from_dict({"a": 5, "b": 6})
        >>> table.add_rows([row1, row2])
           a  b
        0  1  2
        1  3  4
        2  5  6
        """
        import pandas as pd

        if isinstance(rows, Table):
            if rows.number_of_columns == 0:
                return self
            if self.number_of_columns == 0:
                return rows
            different_column_names = set(self.column_names) - set(rows.column_names)
            if len(different_column_names) > 0:
                raise UnknownColumnNameError(
                    sorted(
                        different_column_names,
                        key={val: ix for ix, val in enumerate(self.column_names)}.__getitem__,
                    ),
                )
            if rows.number_of_rows == 0:
                return self
            if self.number_of_rows == 0:
                return rows

            new_df = pd.concat([self._data, rows._data]).infer_objects()
            new_df.columns = self.column_names
            schema = Schema._merge_multiple_schemas([self.schema, rows.schema])
            return Table._from_pandas_dataframe(new_df, schema)

        if len(rows) == 0:
            return self

        different_column_names = set()
        for row in rows:
            different_column_names.update(set(self.column_names) - set(row.column_names))
        if len(different_column_names) > 0:
            raise UnknownColumnNameError(
                sorted(
                    different_column_names,
                    key={val: ix for ix, val in enumerate(self.column_names)}.__getitem__,
                ),
            )

        result = self
        for row in rows:
            result = result.add_row(row)

        return result

    def filter_rows(self, query: Callable[[Row], bool]) -> Table:
        """
        Return a new table with rows filtered by Callable (e.g. lambda function).

        The original table is not modified.

        Parameters
        ----------
        query : lambda function
            A Callable that is applied to all rows.

        Returns
        -------
        table : Table
            A table containing only the rows filtered by the query.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
        >>> table.filter_rows(lambda x: x["a"] < 2)
           a  b
        0  1  2
        """
        import pandas as pd

        rows: list[Row] = [row for row in self.to_rows() if query(row)]
        if len(rows) == 0:
            result_table = Table._from_pandas_dataframe(pd.DataFrame(), self._schema)
        else:
            result_table = self.from_rows(rows)
        return result_table

    _T = TypeVar("_T")

    def group_rows_by(self, key_selector: Callable[[Row], _T]) -> dict[_T, Table]:
        """
        Return a dictionary with copies of the output tables as values and the keys from the key_selector.

        The original table is not modified.

        Parameters
        ----------
        key_selector : Callable[[Row], _T]
            A Callable that is applied to all rows and returns the key of the group.

        Returns
        -------
        dictionary : dict
            A dictionary containing the new tables as values and the selected keys as keys.
        """
        dictionary: dict[Table._T, Table] = {}
        for row in self.to_rows():
            if key_selector(row) in dictionary:
                dictionary[key_selector(row)] = dictionary[key_selector(row)].add_row(row)
            else:
                dictionary[key_selector(row)] = Table.from_rows([row])
        return dictionary

    def keep_only_columns(self, column_names: list[str]) -> Table:
        """
        Return a new table with only the given column(s).

        The original table is not modified.

        Note: When removing the last column of the table, the `number_of_columns` property will be set to 0.

        Parameters
        ----------
        column_names : list[str]
            A list containing only the columns to be kept.

        Returns
        -------
        table : Table
            A table containing only the given column(s).

        Raises
        ------
        UnknownColumnNameError
            If any of the given columns does not exist.
        IllegalSchemaModificationError
            If removing the columns would violate an invariant in the subclass.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
        >>> table.keep_only_columns(["b"])
           b
        0  2
        1  4
        """
        invalid_columns = []
        similar_columns: list[str] = []
        for name in column_names:
            if not self._schema.has_column(name):
                similar_columns = similar_columns + self._get_similar_columns(name)
                invalid_columns.append(name)
        if len(invalid_columns) != 0:
            raise UnknownColumnNameError(invalid_columns, similar_columns)

        return self.remove_columns(list(set(self.column_names) - set(column_names)))

    def remove_columns(self, column_names: list[str]) -> Table:
        """
        Return a new table without the given column(s).

        The original table is not modified.

        Note: When removing the last column of the table, the `number_of_columns` property will be set to 0.

        Parameters
        ----------
        column_names : list[str]
            A list containing all columns to be dropped.

        Returns
        -------
        table : Table
            A table without the given columns.

        Raises
        ------
        UnknownColumnNameError
            If any of the given columns does not exist.
        IllegalSchemaModificationError
            If removing the columns would violate an invariant in the subclass.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
        >>> table.remove_columns(["b"])
           a
        0  1
        1  3
        """
        invalid_columns = []
        similar_columns: list[str] = []
        for name in column_names:
            if not self._schema.has_column(name):
                similar_columns = similar_columns + self._get_similar_columns(name)
                invalid_columns.append(name)
        if len(invalid_columns) != 0:
            raise UnknownColumnNameError(invalid_columns, similar_columns)

        transformed_data = self._data.drop(labels=column_names, axis="columns")
        transformed_data.columns = [name for name in self._schema.column_names if name not in column_names]

        if len(transformed_data.columns) == 0:
            return Table()

        return Table._from_pandas_dataframe(transformed_data)

    def remove_columns_with_missing_values(self) -> Table:
        """
        Return a new table without the columns that contain missing values.

        The original table is not modified.

        Note: When removing the last column of the table, the `number_of_columns` property will be set to 0.

        Returns
        -------
        table : Table
            A table without the columns that contain missing values.

        Raises
        ------
        IllegalSchemaModificationError
            If removing the columns would violate an invariant in the subclass.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1, 2], "b": [None, 2]})
        >>> table.remove_columns_with_missing_values()
           a
        0  1
        1  2
        """
        return Table.from_columns([column for column in self.to_columns() if not column.has_missing_values()])

    def remove_columns_with_non_numerical_values(self) -> Table:
        """
        Return a new table without the columns that contain non-numerical values.

        The original table is not modified.

        Note: When removing the last column of the table, the `number_of_columns` property will be set to 0.

        Returns
        -------
        table : Table
            A table without the columns that contain non-numerical values.

        Raises
        ------
        IllegalSchemaModificationError
            If removing the columns would violate an invariant in the subclass.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1, 0], "b": ["test", 2]})
        >>> table.remove_columns_with_non_numerical_values()
           a
        0  1
        1  0
        """
        return Table.from_columns([column for column in self.to_columns() if column.type.is_numeric()])

    def remove_duplicate_rows(self) -> Table:
        """
        Return a new table with every duplicate row removed.

        The original table is not modified.

        Returns
        -------
        result : Table
            The table with the duplicate rows removed.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1, 3, 3], "b": [2, 4, 4]})
        >>> table.remove_duplicate_rows()
           a  b
        0  1  2
        1  3  4
        """
        result = self._data.drop_duplicates(ignore_index=True)
        result.columns = self._schema.column_names
        return Table._from_pandas_dataframe(result)

    def remove_rows_with_missing_values(self) -> Table:
        """
        Return a new table without the rows that contain missing values.

        The original table is not modified.

        Returns
        -------
        table : Table
            A table without the rows that contain missing values.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1.0, None, 3], "b": [2, 4.0, None]})
        >>> table.remove_rows_with_missing_values()
             a    b
        0  1.0  2.0
        """
        result = self._data.dropna(axis="index")
        return Table._from_pandas_dataframe(result)

    def remove_rows_with_outliers(self) -> Table:
        """
        Return a new table without those rows that contain at least one outlier.

        We define an outlier as a value that has a distance of more than 3 standard deviations from the column mean.
        Missing values are not considered outliers. They are also ignored during the calculation of the standard
        deviation.

        The original table is not modified.

        Returns
        -------
        new_table : Table
            A new table without rows containing outliers.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Column, Table
        >>> c1 = Column("a", [1, 3, 1, 0.1, 0, 0, 0, 0, 0, 0, 0, 0])
        >>> c2 = Column("b", [1.5, 1, 0.5, 0.01, 0, 0, 0, 0, 0, 0, 0, 0])
        >>> c3 = Column("c", [0.1, 0.00, 0.4, 0.2, 0, 0, 0, 0, 0, 0, 0, 0])
        >>> c4 = Column("d", [-1000000, 1000000, -1000000, -1000000, -1000000, -1000000, -1000000, -1000000, -1000000, -1000000, -1000000, -1000000])
        >>> table = Table.from_columns([c1, c2, c3, c4])
        >>> table.remove_rows_with_outliers()
              a     b    c        d
        0   1.0  1.50  0.1 -1000000
        1   1.0  0.50  0.4 -1000000
        2   0.1  0.01  0.2 -1000000
        3   0.0  0.00  0.0 -1000000
        4   0.0  0.00  0.0 -1000000
        5   0.0  0.00  0.0 -1000000
        6   0.0  0.00  0.0 -1000000
        7   0.0  0.00  0.0 -1000000
        8   0.0  0.00  0.0 -1000000
        9   0.0  0.00  0.0 -1000000
        10  0.0  0.00  0.0 -1000000
        """
        import numpy as np
        from scipy import stats

        table_without_nonnumericals = self.remove_columns_with_non_numerical_values()
        z_scores = np.absolute(stats.zscore(table_without_nonnumericals._data, nan_policy="omit"))
        filter_ = ((z_scores < 3) | np.isnan(z_scores)).all(axis=1)

        return Table._from_pandas_dataframe(self._data[filter_], self._schema)

    def rename_column(self, old_name: str, new_name: str) -> Table:
        """
        Return a new `Table` with a single column renamed.

        The original table is not modified.

        Parameters
        ----------
        old_name : str
            The old name of the target column.
        new_name : str
            The new name of the target column.

        Returns
        -------
        table : Table
            The Table with the renamed column.

        Raises
        ------
        UnknownColumnNameError
            If the specified old target column name does not exist.
        DuplicateColumnNameError
            If the specified new target column name already exists.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1], "b": [2]})
        >>> table.rename_column("b", "c")
           a  c
        0  1  2
        """
        if old_name not in self._schema.column_names:
            similar_columns = self._get_similar_columns(old_name)
            raise UnknownColumnNameError([old_name], similar_columns)
        if old_name == new_name:
            return self
        if new_name in self._schema.column_names:
            raise DuplicateColumnNameError(new_name)

        new_df = self._data.reset_index(drop=True)
        new_df.columns = self._schema.column_names
        return Table._from_pandas_dataframe(new_df.rename(columns={old_name: new_name}))

    def replace_column(self, old_column_name: str, new_columns: list[Column]) -> Table:
        """
        Return a new table with the specified old column replaced by a list of new columns.

        The order of columns is kept.

        The original table is not modified.

        Parameters
        ----------
        old_column_name : str
            The name of the column to be replaced.

        new_columns : list[Column]
            The list of new columns replacing the old column.

        Returns
        -------
        result : Table
            A table with the old column replaced by the new columns.

        Raises
        ------
        UnknownColumnNameError
            If the old column does not exist.
        DuplicateColumnNameError
            If at least one of the new columns already exists and the existing column is not affected by the replacement.
        ColumnSizeError
            If the size of at least one of the new columns does not match the amount of rows.
        IllegalSchemaModificationError
            If replacing the column would violate an invariant in the subclass.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Column, Table
        >>> table = Table.from_dict({"a": [1], "b": [2]})
        >>> new_col = Column("new", [3])
        >>> table.replace_column("b", [new_col])
           a  new
        0  1    3
        """
        if old_column_name not in self._schema.column_names:
            similar_columns = self._get_similar_columns(old_column_name)
            raise UnknownColumnNameError([old_column_name], similar_columns)

        columns = list[Column]()
        for old_column in self.column_names:
            if old_column == old_column_name:
                for new_column in new_columns:
                    if new_column.name in self.column_names and new_column.name != old_column_name:
                        raise DuplicateColumnNameError(new_column.name)

                    if self.number_of_rows != new_column.number_of_rows:
                        raise ColumnSizeError(str(self.number_of_rows), str(new_column.number_of_rows))
                    columns.append(new_column)
            else:
                columns.append(self.get_column(old_column))

        return Table.from_columns(columns)

    def shuffle_rows(self) -> Table:
        """
        Return a new `Table` with randomly shuffled rows of this `Table`.

        The original table is not modified.

        Returns
        -------
        result : Table
            The shuffled Table.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> import numpy as np
        >>> np.random.seed(123456)
        >>> table = Table.from_dict({"a": [1, 3, 5], "b": [2, 4, 6]})
        >>> table.shuffle_rows()
           a  b
        0  5  6
        1  1  2
        2  3  4
        """
        new_df = self._data.sample(frac=1.0)
        new_df.columns = self._schema.column_names
        return Table._from_pandas_dataframe(new_df)

    def slice_rows(
        self,
        start: int | None = None,
        end: int | None = None,
        step: int = 1,
    ) -> Table:
        """
        Slice a part of the table into a new table.

        The original table is not modified.

        Parameters
        ----------
        start : int | None
            The first index of the range to be copied into a new table, None by default.
        end : int | None
            The last index of the range to be copied into a new table, None by default.
        step : int
            The step size used to iterate through the table, 1 by default.

        Returns
        -------
        result : Table
            The resulting table.

        Raises
        ------
        IndexOutOfBoundsError
            If the index is out of bounds.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1, 3, 5], "b": [2, 4, 6]})
        >>> table.slice_rows(0, 2)
           a  b
        0  1  2
        1  3  4
        """
        if start is None:
            start = 0

        if end is None:
            end = self.number_of_rows

        if end < start:
            raise IndexOutOfBoundsError(slice(start, end))
        if start < 0 or end < 0 or start > self.number_of_rows or end > self.number_of_rows:
            raise IndexOutOfBoundsError(start if start < 0 or start > self.number_of_rows else end)

        new_df = self._data.iloc[start:end:step]
        new_df.columns = self._schema.column_names
        return Table._from_pandas_dataframe(new_df)

    def sort_columns(
        self,
        comparator: Callable[[Column, Column], int] = lambda col1, col2: (col1.name > col2.name)
        - (col1.name < col2.name),
    ) -> Table:
        """
        Sort the columns of a `Table` with the given comparator and return a new `Table`.

        The comparator is a function that takes two columns `col1` and `col2` and
        returns an integer:

        * If `col1` should be ordered before `col2`, the function should return a negative number.
        * If `col1` should be ordered after `col2`, the function should return a positive number.
        * If the original order of `col1` and `col2` should be kept, the function should return 0.

        If no comparator is given, the columns will be sorted alphabetically by their name.

        The original table is not modified.

        Parameters
        ----------
        comparator : Callable[[Column, Column], int]
            The function used to compare two columns.

        Returns
        -------
        new_table : Table
            A new table with sorted columns.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1], "b": [2] })
        >>> table.sort_columns(lambda col1, col2: 1)
           a  b
        0  1  2
        >>> table.sort_columns(lambda col1, col2: -1)
           b  a
        0  2  1
        >>> table2 = Table.from_dict({"b": [2], "a": [1]})
        >>> table2.sort_columns()
           a  b
        0  1  2
        """
        columns = self.to_columns()
        columns.sort(key=functools.cmp_to_key(comparator))
        return Table.from_columns(columns)

    def sort_rows(self, comparator: Callable[[Row, Row], int]) -> Table:
        """
        Sort the rows of a `Table` with the given comparator and return a new `Table`.

        The comparator is a function that takes two rows `row1` and `row2` and
        returns an integer:

        * If `row1` should be ordered before `row2`, the function should return a negative number.
        * If `row1` should be ordered after `row2`, the function should return a positive number.
        * If the original order of `row1` and `row2` should be kept, the function should return 0.

        The original table is not modified.

        Parameters
        ----------
        comparator : Callable[[Row, Row], int]
            The function used to compare two rows.

        Returns
        -------
        new_table : Table
            A new table with sorted rows.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1, 3, 5], "b": [2, 4, 6] })
        >>> table.sort_rows(lambda row1, row2: 1)
           a  b
        0  1  2
        1  3  4
        2  5  6
        >>> table.sort_rows(lambda row1, row2: -1)
           a  b
        0  5  6
        1  3  4
        2  1  2
        >>> table.sort_rows(lambda row1, row2: 0)
           a  b
        0  1  2
        1  3  4
        2  5  6
        """
        rows = self.to_rows()
        rows.sort(key=functools.cmp_to_key(comparator))
        return Table.from_rows(rows)

    def split_rows(self, percentage_in_first: float) -> tuple[Table, Table]:
        """
        Split the table into two new tables.

        The original table is not modified.

        Parameters
        ----------
        percentage_in_first : float
            The desired size of the first table in percentage to the given table; must be between 0 and 1.

        Returns
        -------
        result : (Table, Table)
            A tuple containing the two resulting tables. The first table has the specified size, the second table
            contains the rest of the data.

        Raises
        ------
        ValueError:
            if the 'percentage_in_first' is not between 0 and 1.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"temperature": [10, 15, 20, 25, 30], "sales": [54, 74, 90, 206, 210]})
        >>> slices = table.split_rows(0.4)
        >>> slices[0]
           temperature  sales
        0           10     54
        1           15     74
        >>> slices[1]
           temperature  sales
        0           20     90
        1           25    206
        2           30    210
        """
        if percentage_in_first < 0 or percentage_in_first > 1:
            raise ValueError("The given percentage is not between 0 and 1")
        if self.number_of_rows == 0:
            return Table(), Table()
        return (
            self.slice_rows(0, round(percentage_in_first * self.number_of_rows)),
            self.slice_rows(round(percentage_in_first * self.number_of_rows)),
        )

    def tag_columns(self, target_name: str, feature_names: list[str] | None = None) -> TaggedTable:
        """
        Return a new `TaggedTable` with columns marked as a target column or feature columns.

        The original table is not modified.

        Parameters
        ----------
        target_name : str
            Name of the target column.
        feature_names : list[str] | None
            Names of the feature columns. If None, all columns except the target column are used.

        Returns
        -------
        tagged_table : TaggedTable
            A new tagged table with the given target and feature names.

        Raises
        ------
        ValueError
            If the target column is also a feature column.
        ValueError
            If no feature columns are specified.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table, TaggedTable
        >>> table = Table.from_dict({"item": ["apple", "milk", "beer"], "price": [1.10, 1.19, 1.79], "amount_bought": [74, 72, 51]})
        >>> tagged_table = table.tag_columns(target_name="amount_bought", feature_names=["item", "price"])
        """
        from ._tagged_table import TaggedTable

        return TaggedTable._from_table(self, target_name, feature_names)

    def time_columns(self, target_name: str, time_name: str, feature_names: list[str] | None = None) -> TimeSeries:
        """
        Return a new `TimeSeries` with columns marked as a target and time column or feature columns.

        The original table is not modified.

        Parameters
        ----------
        target_name : str
            Name of the target column.
        time_name : str
            Name of the time column.
        feature_names : list[str] | None
            Names of the feature columns. If None, all columns except the target and time columns are used.

        Returns
        -------
        time_series : TimeSeries
            A new time series with the given target, time and feature names.

        Raises
        ------
        ValueError
            If the target column is also a feature column.
        ValueError
            If there is no other column than the specified target and time columns left to be a feature column

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table, TimeSeries
        >>> table = Table.from_dict({"time": ["01.01", "01.02", "01.03"], "price": [1.10, 1.19, 1.79], "amount_bought": [74, 72, 51]})
        >>> tagged_table = table.time_columns(target_name="amount_bought",time_name = "time", feature_names=["price"])
        """
        from ._time_series import TimeSeries

        return TimeSeries._from_table(self, target_name, time_name, feature_names)

    def transform_column(self, name: str, transformer: Callable[[Row], Any]) -> Table:
        """
        Return a new `Table` with the provided column transformed by calling the provided transformer.

        The original table is not modified.

        Returns
        -------
        result : Table
            The table with the transformed column.

        Raises
        ------
        UnknownColumnNameError
            If the column does not exist.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"item": ["apple", "milk", "beer"], "price": [1.00, 1.19, 1.79]})
        >>> table.transform_column("price", lambda row: row.get_value("price") * 100)
            item  price
        0  apple  100.0
        1   milk  119.0
        2   beer  179.0
        """
        if self.has_column(name):
            items: list = [transformer(item) for item in self.to_rows()]
            result: list[Column] = [Column(name, items)]
            return self.replace_column(name, result)
        similar_columns = self._get_similar_columns(name)
        raise UnknownColumnNameError([name], similar_columns)

    def transform_table(self, transformer: TableTransformer) -> Table:
        """
        Return a new `Table` with a learned transformation applied to this table.

        The original table is not modified.

        Parameters
        ----------
        transformer : TableTransformer
            The transformer which transforms the given table.

        Returns
        -------
        transformed_table : Table
            The transformed table.

        Raises
        ------
        TransformerNotFittedError
            If the transformer has not been fitted yet.
        IllegalSchemaModificationError
            If replacing the column would violate an invariant in the subclass.

        Examples
        --------
        >>> from safeds.data.tabular.transformation import OneHotEncoder
        >>> from safeds.data.tabular.containers import Table
        >>> transformer = OneHotEncoder()
        >>> table = Table.from_dict({"fruit": ["apple", "pear", "apple"], "pet": ["dog", "duck", "duck"]})
        >>> transformer = transformer.fit(table, None)
        >>> table.transform_table(transformer)
           fruit__apple  fruit__pear  pet__dog  pet__duck
        0           1.0          0.0       1.0        0.0
        1           0.0          1.0       0.0        1.0
        2           1.0          0.0       0.0        1.0
        """
        return transformer.transform(self)

    def inverse_transform_table(self, transformer: InvertibleTableTransformer) -> Table:
        """
        Return a new `Table` with the inverted transformation applied by the given transformer.

        The original table is not modified.

        Parameters
        ----------
        transformer : InvertibleTableTransformer
            A transformer that was fitted with columns, which are all present in the table.

        Returns
        -------
        table : Table
            The original table.

        Raises
        ------
        TransformerNotFittedError
            If the transformer has not been fitted yet.

        Examples
        --------
        >>> from safeds.data.tabular.transformation import OneHotEncoder
        >>> from safeds.data.tabular.containers import Table
        >>> transformer = OneHotEncoder()
        >>> table = Table.from_dict({"a": ["j", "k", "k"], "b": ["x", "y", "x"]})
        >>> transformer = transformer.fit(table, None)
        >>> transformed_table = transformer.transform(table)
        >>> transformed_table.inverse_transform_table(transformer)
           a  b
        0  j  x
        1  k  y
        2  k  x
        >>> transformer.inverse_transform(transformed_table)
           a  b
        0  j  x
        1  k  y
        2  k  x
        """
        return transformer.inverse_transform(self)

    # ------------------------------------------------------------------------------------------------------------------
    # Plotting
    # ------------------------------------------------------------------------------------------------------------------

    def plot_correlation_heatmap(self) -> Image:
        """
        Plot a correlation heatmap for all numerical columns of this `Table`.

        Returns
        -------
        plot: Image
            The plot as an image.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"temperature": [10, 15, 20, 25, 30], "sales": [54, 74, 90, 206, 210]})
        >>> image = table.plot_correlation_heatmap()
        """
        import matplotlib.pyplot as plt
        import seaborn as sns

        only_numerical = self.remove_columns_with_non_numerical_values()

        if self.number_of_rows == 0:
            warnings.warn(
                "An empty table has been used. A correlation heatmap on an empty table will show nothing.",
                stacklevel=2,
            )

            with warnings.catch_warnings():
                warnings.filterwarnings(
                    "ignore",
                    message=(
                        "Attempting to set identical low and high (xlims|ylims) makes transformation singular;"
                        " automatically expanding."
                    ),
                )
                fig = plt.figure()
                sns.heatmap(
                    data=only_numerical._data.corr(),
                    vmin=-1,
                    vmax=1,
                    xticklabels=only_numerical.column_names,
                    yticklabels=only_numerical.column_names,
                    cmap="vlag",
                )
                plt.tight_layout()
        else:
            fig = plt.figure()
            sns.heatmap(
                data=only_numerical._data.corr(),
                vmin=-1,
                vmax=1,
                xticklabels=only_numerical.column_names,
                yticklabels=only_numerical.column_names,
                cmap="vlag",
            )
            plt.tight_layout()

        buffer = io.BytesIO()
        fig.savefig(buffer, format="png")
        plt.close()  # Prevents the figure from being displayed directly
        buffer.seek(0)
        return Image.from_bytes(buffer.read())

    def plot_lineplot(self, x_column_name: str, y_column_name: str) -> Image:
        """
        Plot two columns against each other in a lineplot.

        If there are multiple x-values for a y-value, the resulting plot will consist of a line representing the mean
        and the lower-transparency area around the line representing the 95% confidence interval.

        Parameters
        ----------
        x_column_name : str
            The column name of the column to be plotted on the x-Axis.
        y_column_name : str
            The column name of the column to be plotted on the y-Axis.

        Returns
        -------
        plot: Image
            The plot as an image.

        Raises
        ------
        UnknownColumnNameError
            If either of the columns do not exist.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"temperature": [10, 15, 20, 25, 30], "sales": [54, 74, 90, 206, 210]})
        >>> image = table.plot_lineplot("temperature", "sales")
        """
        import matplotlib.pyplot as plt
        import seaborn as sns

        if not self.has_column(x_column_name) or not self.has_column(y_column_name):
            similar_columns_x = self._get_similar_columns(x_column_name)
            similar_columns_y = self._get_similar_columns(y_column_name)
            raise UnknownColumnNameError(
                ([x_column_name] if not self.has_column(x_column_name) else [])
                + ([y_column_name] if not self.has_column(y_column_name) else []),
                (similar_columns_x if not self.has_column(x_column_name) else [])
                + (similar_columns_y if not self.has_column(y_column_name) else []),
            )

        fig = plt.figure()
        ax = sns.lineplot(
            data=self._data,
            x=x_column_name,
            y=y_column_name,
        )
        ax.set(xlabel=x_column_name, ylabel=y_column_name)
        ax.set_xticks(ax.get_xticks())
        ax.set_xticklabels(
            ax.get_xticklabels(),
            rotation=45,
            horizontalalignment="right",
        )  # rotate the labels of the x Axis to prevent the chance of overlapping of the labels
        plt.tight_layout()

        buffer = io.BytesIO()
        fig.savefig(buffer, format="png")
        plt.close()  # Prevents the figure from being displayed directly
        buffer.seek(0)
        return Image.from_bytes(buffer.read())

    def plot_scatterplot(self, x_column_name: str, y_column_name: str) -> Image:
        """
        Plot two columns against each other in a scatterplot.

        Parameters
        ----------
        x_column_name : str
            The column name of the column to be plotted on the x-Axis.
        y_column_name : str
            The column name of the column to be plotted on the y-Axis.

        Returns
        -------
        plot: Image
            The plot as an image.

        Raises
        ------
        UnknownColumnNameError
            If either of the columns do not exist.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"temperature": [10, 15, 20, 25, 30], "sales": [54, 74, 90, 206, 210]})
        >>> image = table.plot_scatterplot("temperature", "sales")
        """
        import matplotlib.pyplot as plt
        import seaborn as sns

        if not self.has_column(x_column_name) or not self.has_column(y_column_name):
            similar_columns_x = self._get_similar_columns(x_column_name)
            similar_columns_y = self._get_similar_columns(y_column_name)
            raise UnknownColumnNameError(
                ([x_column_name] if not self.has_column(x_column_name) else [])
                + ([y_column_name] if not self.has_column(y_column_name) else []),
                (similar_columns_x if not self.has_column(x_column_name) else [])
                + (similar_columns_y if not self.has_column(y_column_name) else []),
            )

        fig = plt.figure()
        ax = sns.scatterplot(
            data=self._data,
            x=x_column_name,
            y=y_column_name,
        )
        ax.set(xlabel=x_column_name, ylabel=y_column_name)
        ax.set_xticks(ax.get_xticks())
        ax.set_xticklabels(
            ax.get_xticklabels(),
            rotation=45,
            horizontalalignment="right",
        )  # rotate the labels of the x Axis to prevent the chance of overlapping of the labels
        plt.tight_layout()

        buffer = io.BytesIO()
        fig.savefig(buffer, format="png")
        plt.close()  # Prevents the figure from being displayed directly
        buffer.seek(0)
        return Image.from_bytes(buffer.read())

    def plot_boxplots(self) -> Image:
        """
        Plot a boxplot for every numerical column.

        Returns
        -------
        plot: Image
            The plot as an image.

        Raises
        ------
        NonNumericColumnError
            If the table contains only non-numerical columns.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table({"a":[1, 2], "b": [3, 42]})
        >>> image = table.plot_boxplots()
        """
        import matplotlib.pyplot as plt
        import pandas as pd
        import seaborn as sns

        numerical_table = self.remove_columns_with_non_numerical_values()
        if numerical_table.number_of_columns == 0:
            raise NonNumericColumnError("This table contains only non-numerical columns.")
        col_wrap = min(numerical_table.number_of_columns, 3)

        data = pd.melt(numerical_table._data, value_vars=numerical_table.column_names)
        grid = sns.FacetGrid(data, col="variable", col_wrap=col_wrap, sharex=False, sharey=False)
        with warnings.catch_warnings():
            warnings.filterwarnings(
                "ignore",
                message="Using the boxplot function without specifying `order` is likely to produce an incorrect plot.",
            )
            grid.map(sns.boxplot, "variable", "value")
        grid.set_xlabels("")
        grid.set_ylabels("")
        grid.set_titles("{col_name}")
        for axes in grid.axes.flat:
            axes.set_xticks([])
        plt.tight_layout()
        fig = grid.fig

        buffer = io.BytesIO()
        fig.savefig(buffer, format="png")
        plt.close()  # Prevents the figure from being displayed directly
        buffer.seek(0)
        return Image.from_bytes(buffer.read())

    def plot_histograms(self) -> Image:
        """
        Plot a histogram for every column.

        Returns
        -------
        plot: Image
            The plot as an image.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table({"a": [2, 3, 5, 1], "b": [54, 74, 90, 2014]})
        >>> image = table.plot_histograms()
        """
        import matplotlib.pyplot as plt
        import pandas as pd
        import seaborn as sns

        col_wrap = min(self.number_of_columns, 3)

        data = pd.melt(self._data.map(lambda value: str(value)), value_vars=self.column_names)
        grid = sns.FacetGrid(data=data, col="variable", col_wrap=col_wrap, sharex=False, sharey=False)
        grid.map(sns.histplot, "value")
        grid.set_xlabels("")
        grid.set_ylabels("")
        grid.set_titles("{col_name}")
        for axes in grid.axes.flat:
            axes.set_xticks(axes.get_xticks())
            axes.set_xticklabels(axes.get_xticklabels(), rotation=45, horizontalalignment="right")
        grid.tight_layout()
        fig = grid.fig

        buffer = io.BytesIO()
        fig.savefig(buffer, format="png")
        plt.close()
        buffer.seek(0)
        return Image.from_bytes(buffer.read())

    # ------------------------------------------------------------------------------------------------------------------
    # Conversion
    # ------------------------------------------------------------------------------------------------------------------

    def to_csv_file(self, path: str | Path) -> None:
        """
        Write the data from the table into a CSV file.

        If the file and/or the directories do not exist they will be created. If the file already exists it will be
        overwritten.

        Parameters
        ----------
        path : str | Path
            The path to the output file.

        Raises
        ------
        WrongFileExtensionError
            If the file is not a csv file.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1, 2, 3], "b": [4, 5, 6]})
        >>> table.to_csv_file("./src/resources/to_csv_file.csv")
        """
        path = Path(path)
        if path.suffix != ".csv":
            raise WrongFileExtensionError(path, ".csv")
        path.parent.mkdir(parents=True, exist_ok=True)
        data_to_csv = self._data.reset_index(drop=True)
        data_to_csv.columns = self._schema.column_names
        data_to_csv.to_csv(path, index=False)

    def to_excel_file(self, path: str | Path) -> None:
        """
        Write the data from the table into an Excel file.

        Valid file extensions are `.xls`, '.xlsx', `.xlsm`, `.xlsb`, `.odf`, `.ods` and `.odt`.
        If the file and/or the directories do not exist, they will be created. If the file already exists, it will be
        overwritten.

        Parameters
        ----------
        path : str | Path
            The path to the output file.

        Raises
        ------
        WrongFileExtensionError
            If the file is not an Excel file.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1, 2, 3], "b": [4, 5, 6]})
        >>> table.to_excel_file("./src/resources/to_excel_file.xlsx")
        """
        import openpyxl

        path = Path(path)
        excel_extensions = [".xls", ".xlsx", ".xlsm", ".xlsb", ".odf", ".ods", ".odt"]
        if path.suffix not in excel_extensions:
            raise WrongFileExtensionError(path, excel_extensions)

        # Create Excel metadata in the file
        tmp_table_file = openpyxl.Workbook()
        tmp_table_file.save(path)

        path.parent.mkdir(parents=True, exist_ok=True)
        data_to_excel = self._data.reset_index(drop=True)
        data_to_excel.columns = self._schema.column_names
        data_to_excel.to_excel(path)

    def to_json_file(self, path: str | Path) -> None:
        """
        Write the data from the table into a JSON file.

        If the file and/or the directories do not exist, they will be created. If the file already exists it will be
        overwritten.

        Parameters
        ----------
        path : str | Path
            The path to the output file.

        Raises
        ------
        WrongFileExtensionError
            If the file is not a JSON file.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a": [1, 2, 3], "b": [4, 5, 6]})
        >>> table.to_json_file("./src/resources/to_json_file.json")
        """
        path = Path(path)
        if path.suffix != ".json":
            raise WrongFileExtensionError(path, ".json")
        path.parent.mkdir(parents=True, exist_ok=True)
        data_to_json = self._data.reset_index(drop=True)
        data_to_json.columns = self._schema.column_names
        data_to_json.to_json(path)

    def to_dict(self) -> dict[str, list[Any]]:
        """
        Return a dictionary that maps column names to column values.

        Returns
        -------
        data : dict[str, list[Any]]
            Dictionary representation of the table.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> row1 = Row({"a": 1, "b": 5})
        >>> row2 = Row({"a": 2, "b": 6})
        >>> table1 = Table.from_rows([row1, row2])
        >>> table2 = Table.from_dict({"a": [1, 2], "b": [5, 6]})
        >>> table1 == table2
        True
        """
        return {column_name: list(self.get_column(column_name)) for column_name in self.column_names}

    def to_html(self) -> str:
        """
        Return an HTML representation of the table.

        Returns
        -------
        output : str
            The generated HTML.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table({"a": [1, 2, 3], "b": [4, 5, 6]})
        >>> html = table.to_html()
        """
        return self._data.to_html(max_rows=self._data.shape[0], max_cols=self._data.shape[1])

    def to_columns(self) -> list[Column]:
        """
        Return a list of the columns.

        Returns
        -------
        columns : list[Columns]
            List of columns.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a":[1, 2],"b":[20, 30]})
        >>> table.to_columns()
        [Column('a', [1, 2]), Column('b', [20, 30])]
        """
        return [self.get_column(name) for name in self._schema.column_names]

    def to_rows(self) -> list[Row]:
        """
        Return a list of the rows.

        Returns
        -------
        rows : list[Row]
            List of rows.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table.from_dict({"a":[1, 2],"b":[20, 30]})
        >>> table.to_rows()
        [Row({
            'a': 1,
            'b': 20
        }), Row({
            'a': 2,
            'b': 30
        })]
        """
        import pandas as pd

        return [
            Row._from_pandas_dataframe(
                pd.DataFrame([list(series_row)], columns=self._schema.column_names),
                self._schema,
            )
            for (_, series_row) in self._data.iterrows()
        ]

    # ------------------------------------------------------------------------------------------------------------------
    # IPython integration
    # ------------------------------------------------------------------------------------------------------------------

    def _repr_html_(self) -> str:
        """
        Return an HTML representation of the table.

        Returns
        -------
        output : str
            The generated HTML.
        """
        return self._data.to_html(max_rows=self._data.shape[0], max_cols=self._data.shape[1], notebook=True)

    # ------------------------------------------------------------------------------------------------------------------
    # Dataframe interchange protocol
    # ------------------------------------------------------------------------------------------------------------------

    def __dataframe__(self, nan_as_null: bool = False, allow_copy: bool = True):  # type: ignore[no-untyped-def]
        """
        Return a DataFrame exchange object that conforms to the dataframe interchange protocol.

        Generally, there is no reason to call this method directly. The dataframe interchange protocol is designed to
        allow libraries to consume tabular data from different sources, such as `pandas` or `polars`. If you still
        decide to call this method, you should not rely on any capabilities of the returned object beyond the dataframe
        interchange protocol.

        The specification of the dataframe interchange protocol can be found on
        [GitHub](https://github.com/data-apis/dataframe-api).

        Parameters
        ----------
        nan_as_null : bool
            Whether to replace missing values in the data with `NaN`.
        allow_copy : bool
            Whether memory may be copied to create the DataFrame exchange object.

        Returns
        -------
        dataframe
            A DataFrame object that conforms to the dataframe interchange protocol.
        """
        if not allow_copy:
            raise NotImplementedError("For the moment we need to copy the data, so `allow_copy` must be True.")

        data_copy = self._data.reset_index(drop=True)
        data_copy.columns = self.column_names
        return data_copy.__dataframe__(nan_as_null, allow_copy)

    def _into_dataloader(self, batch_size: int) -> DataLoader:
        """
        Return a Dataloader for the data stored in this table, used for predicting with neural networks.

        The original table is not modified.

        Parameters
        ----------
        batch_size
            The size of data batches that should be loaded at one time.

        Returns
        -------
        result :
            The DataLoader.

        """
        import numpy as np
        from torch.utils.data import DataLoader

        features = self.to_rows()
        all_rows = []
        for row in features:
            new_item = []
            for column_name in row:
                new_item.append(row.get_value(column_name))
            all_rows.append(new_item.copy())
        return DataLoader(dataset=_create_dataset(np.array(all_rows)), batch_size=batch_size)

column_names: list[str] property

Return a list of all column names in this table.

Alias for self.schema.column_names -> list[str].

Returns:

Name Type Description
column_names list[str]

The list of the column names.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table.from_dict({"col1": [1, 3], "col2": [2, 4]})
>>> table.column_names
['col1', 'col2']

number_of_columns: int property

Return the number of columns.

Returns:

Name Type Description
number_of_columns int

The number of columns.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table.from_dict({"a": [1], "b": [2]})
>>> table.number_of_columns
2

number_of_rows: int property

Return the number of rows.

Returns:

Name Type Description
number_of_rows int

The number of rows.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table.from_dict({"a": [1], "b": [2]})
>>> table.number_of_rows
1

schema: Schema property

Return the schema of the table.

Returns:

Name Type Description
schema Schema

The schema.

Examples:

>>> from safeds.data.tabular.containers import Row, Table
>>> row = Row({"a": 1, "b": 2.5, "c": "ff"})
>>> table = Table.from_dict({"a": [1, 8], "b": [2.5, 9], "c": ["g", "g"]})
>>> table.schema
Schema({
    'a': Integer,
    'b': RealNumber,
    'c': String
})
>>> table.schema == row.schema
True

__dataframe__(nan_as_null=False, allow_copy=True)

Return a DataFrame exchange object that conforms to the dataframe interchange protocol.

Generally, there is no reason to call this method directly. The dataframe interchange protocol is designed to allow libraries to consume tabular data from different sources, such as pandas or polars. If you still decide to call this method, you should not rely on any capabilities of the returned object beyond the dataframe interchange protocol.

The specification of the dataframe interchange protocol can be found on GitHub.

Parameters:

Name Type Description Default
nan_as_null bool

Whether to replace missing values in the data with NaN.

False
allow_copy bool

Whether memory may be copied to create the DataFrame exchange object.

True

Returns:

Type Description
dataframe

A DataFrame object that conforms to the dataframe interchange protocol.

Source code in src/safeds/data/tabular/containers/_table.py
def __dataframe__(self, nan_as_null: bool = False, allow_copy: bool = True):  # type: ignore[no-untyped-def]
    """
    Return a DataFrame exchange object that conforms to the dataframe interchange protocol.

    Generally, there is no reason to call this method directly. The dataframe interchange protocol is designed to
    allow libraries to consume tabular data from different sources, such as `pandas` or `polars`. If you still
    decide to call this method, you should not rely on any capabilities of the returned object beyond the dataframe
    interchange protocol.

    The specification of the dataframe interchange protocol can be found on
    [GitHub](https://github.com/data-apis/dataframe-api).

    Parameters
    ----------
    nan_as_null : bool
        Whether to replace missing values in the data with `NaN`.
    allow_copy : bool
        Whether memory may be copied to create the DataFrame exchange object.

    Returns
    -------
    dataframe
        A DataFrame object that conforms to the dataframe interchange protocol.
    """
    if not allow_copy:
        raise NotImplementedError("For the moment we need to copy the data, so `allow_copy` must be True.")

    data_copy = self._data.reset_index(drop=True)
    data_copy.columns = self.column_names
    return data_copy.__dataframe__(nan_as_null, allow_copy)

__eq__(other)

Compare two table instances.

Returns:

Type Description
'True' if contents are equal, 'False' otherwise.

Examples:

>>> from safeds.data.tabular.containers import Row, Table
>>> row1 = Row({"a": 1, "b": 2})
>>> row2 = Row({"a": 3, "b": 4})
>>> row3 = Row({"a": 5, "b": 6})
>>> table1 = Table.from_rows([row1, row2])
>>> table2 = Table.from_rows([row1, row2])
>>> table3 = Table.from_rows([row1, row3])
>>> table1 == table2
True
>>> table1 == table3
False
Source code in src/safeds/data/tabular/containers/_table.py
def __eq__(self, other: object) -> bool:
    """
    Compare two table instances.

    Returns
    -------
    'True' if contents are equal, 'False' otherwise.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Row, Table
    >>> row1 = Row({"a": 1, "b": 2})
    >>> row2 = Row({"a": 3, "b": 4})
    >>> row3 = Row({"a": 5, "b": 6})
    >>> table1 = Table.from_rows([row1, row2])
    >>> table2 = Table.from_rows([row1, row2])
    >>> table3 = Table.from_rows([row1, row3])
    >>> table1 == table2
    True
    >>> table1 == table3
    False
    """
    if not isinstance(other, Table):
        return NotImplemented
    if self is other:
        return True
    if self.number_of_columns == 0 and other.number_of_columns == 0:
        return True
    table1 = self.sort_columns()
    table2 = other.sort_columns()
    if table1.number_of_rows == 0 and table2.number_of_rows == 0:
        return table1.column_names == table2.column_names
    return table1._schema == table2._schema and table1._data.equals(table2._data)

__hash__()

Return a deterministic hash value for this table.

Returns:

Name Type Description
hash int

The hash value.

Source code in src/safeds/data/tabular/containers/_table.py
def __hash__(self) -> int:
    """
    Return a deterministic hash value for this table.

    Returns
    -------
    hash:
        The hash value.
    """
    return _structural_hash(self._schema, self.number_of_rows)

__init__(data=None)

Create a table from a mapping of column names to their values.

Parameters:

Name Type Description Default
data Mapping[str, Sequence[Any]] | None

The data. If None, an empty table is created.

None

Raises:

Type Description
ColumnLengthMismatchError

If columns have different lengths.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> Table({"a": [1, 2, 3], "b": [4, 5, 6]})
   a  b
0  1  4
1  2  5
2  3  6
Source code in src/safeds/data/tabular/containers/_table.py
def __init__(self, data: Mapping[str, Sequence[Any]] | None = None) -> None:
    """
    Create a table from a mapping of column names to their values.

    Parameters
    ----------
    data : Mapping[str, Sequence[Any]] | None
        The data. If None, an empty table is created.

    Raises
    ------
    ColumnLengthMismatchError
        If columns have different lengths.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> Table({"a": [1, 2, 3], "b": [4, 5, 6]})
       a  b
    0  1  4
    1  2  5
    2  3  6
    """
    import pandas as pd

    # Enable copy-on-write for pandas dataframes
    pd.options.mode.copy_on_write = True

    if data is None:
        data = {}

    # Validation
    expected_length: int | None = None
    for column_values in data.values():
        if expected_length is None:
            expected_length = len(column_values)
        elif len(column_values) != expected_length:
            raise ColumnLengthMismatchError(
                "\n".join(f"{column_name}: {len(column_values)}" for column_name, column_values in data.items()),
            )

    # Implementation
    self._data: pd.DataFrame = pd.DataFrame(data)
    self._data = self._data.reset_index(drop=True)
    self._schema: Schema = Schema._from_pandas_dataframe(self._data)

__repr__()

Display the table in only one line.

Returns:

Type Description
A string representation of the table in only one line.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
>>> repr(table)
'   a  b\n0  1  2\n1  3  4'
Source code in src/safeds/data/tabular/containers/_table.py
def __repr__(self) -> str:
    r"""
    Display the table in only one line.

    Returns
    -------
    A string representation of the table in only one line.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
    >>> repr(table)
    '   a  b\n0  1  2\n1  3  4'
    """
    tmp = self._data.reset_index(drop=True)
    tmp.columns = self.column_names
    return tmp.__repr__()

__sizeof__()

Return the complete size of this object.

Returns:

Name Type Description
size int

Size of this object in bytes.

Source code in src/safeds/data/tabular/containers/_table.py
def __sizeof__(self) -> int:
    """
    Return the complete size of this object.

    Returns
    -------
    size:
        Size of this object in bytes.
    """
    return sys.getsizeof(self._data) + sys.getsizeof(self._schema)

__str__()

Source code in src/safeds/data/tabular/containers/_table.py
def __str__(self) -> str:
    tmp = self._data.reset_index(drop=True)
    tmp.columns = self.column_names
    return tmp.__str__()

add_column(column)

Return a new table with the provided column attached at the end.

The original table is not modified.

Returns:

Name Type Description
result Table

The table with the column attached.

Raises:

Type Description
DuplicateColumnNameError

If the new column already exists.

ColumnSizeError

If the size of the column does not match the number of rows.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
>>> col = Column("c", ["d", "e"])
>>> table.add_column(col)
   a  b  c
0  1  2  d
1  3  4  e
Source code in src/safeds/data/tabular/containers/_table.py
def add_column(self, column: Column) -> Table:
    """
    Return a new table with the provided column attached at the end.

    The original table is not modified.

    Returns
    -------
    result : Table
        The table with the column attached.

    Raises
    ------
    DuplicateColumnNameError
        If the new column already exists.
    ColumnSizeError
        If the size of the column does not match the number of rows.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
    >>> col = Column("c", ["d", "e"])
    >>> table.add_column(col)
       a  b  c
    0  1  2  d
    1  3  4  e
    """
    if self.has_column(column.name):
        raise DuplicateColumnNameError(column.name)

    if column.number_of_rows != self.number_of_rows and self.number_of_columns != 0:
        raise ColumnSizeError(str(self.number_of_rows), str(column._data.size))

    result = self._data.reset_index(drop=True)
    result.columns = self._schema.column_names
    result[column.name] = column._data
    return Table._from_pandas_dataframe(result)

add_columns(columns)

Return a new Table with multiple added columns.

The original table is not modified.

Parameters:

Name Type Description Default
columns list[Column] or Table

The columns to be added.

required

Returns:

Name Type Description
result Table

A new table combining the original table and the given columns.

Raises:

Type Description
DuplicateColumnNameError

If at least one column name from the provided column list already exists in the table.

ColumnSizeError

If at least one of the column sizes from the provided column list does not match the table.

Examples:

>>> from safeds.data.tabular.containers import Column, Table
>>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
>>> col1 = Column("c", ["d", "e"])
>>> col2 = Column("d", [3.5, 7.9])
>>> table.add_columns([col1, col2])
   a  b  c    d
0  1  2  d  3.5
1  3  4  e  7.9
Source code in src/safeds/data/tabular/containers/_table.py
def add_columns(self, columns: list[Column] | Table) -> Table:
    """
    Return a new `Table` with multiple added columns.

    The original table is not modified.

    Parameters
    ----------
    columns : list[Column] or Table
        The columns to be added.

    Returns
    -------
    result: Table
        A new table combining the original table and the given columns.

    Raises
    ------
    DuplicateColumnNameError
        If at least one column name from the provided column list already exists in the table.
    ColumnSizeError
        If at least one of the column sizes from the provided column list does not match the table.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Column, Table
    >>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
    >>> col1 = Column("c", ["d", "e"])
    >>> col2 = Column("d", [3.5, 7.9])
    >>> table.add_columns([col1, col2])
       a  b  c    d
    0  1  2  d  3.5
    1  3  4  e  7.9
    """
    if isinstance(columns, Table):
        columns = columns.to_columns()
    result = self._data.reset_index(drop=True)
    result.columns = self._schema.column_names
    for column in columns:
        if column.name in result.columns:
            raise DuplicateColumnNameError(column.name)

        if column.number_of_rows != self.number_of_rows and self.number_of_columns != 0:
            raise ColumnSizeError(str(self.number_of_rows), str(column._data.size))

        result[column.name] = column._data
    return Table._from_pandas_dataframe(result)

add_row(row)

Return a new Table with an added Row attached.

If the table happens to be empty beforehand, respective columns will be added automatically.

The order of columns of the new row will be adjusted to the order of columns in the table. The new table will contain the merged schema.

The original table is not modified.

Parameters:

Name Type Description Default
row Row

The row to be added.

required

Returns:

Name Type Description
table Table

A new table with the added row at the end.

Raises:

Type Description
UnknownColumnNameError

If the row has different column names than the table.

Examples:

>>> from safeds.data.tabular.containers import Row, Table
>>> table = Table.from_dict({"a": [1], "b": [2]})
>>> row = Row.from_dict({"a": 3, "b": 4})
>>> table.add_row(row)
   a  b
0  1  2
1  3  4
Source code in src/safeds/data/tabular/containers/_table.py
def add_row(self, row: Row) -> Table:
    """
    Return a new `Table` with an added Row attached.

    If the table happens to be empty beforehand, respective columns will be added automatically.

    The order of columns of the new row will be adjusted to the order of columns in the table.
    The new table will contain the merged schema.

    The original table is not modified.

    Parameters
    ----------
    row : Row
        The row to be added.

    Returns
    -------
    table : Table
        A new table with the added row at the end.

    Raises
    ------
    UnknownColumnNameError
        If the row has different column names than the table.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Row, Table
    >>> table = Table.from_dict({"a": [1], "b": [2]})
    >>> row = Row.from_dict({"a": 3, "b": 4})
    >>> table.add_row(row)
       a  b
    0  1  2
    1  3  4
    """
    import numpy as np
    import pandas as pd

    int_columns = []

    if self.number_of_columns == 0:
        return Table.from_rows([row])
    if len(set(self.column_names) - set(row.column_names)) > 0:
        raise UnknownColumnNameError(
            sorted(
                set(self.column_names) - set(row.column_names),
                key={val: ix for ix, val in enumerate(self.column_names)}.__getitem__,
            ),
        )

    if self.number_of_rows == 0:
        int_columns = list(filter(lambda name: isinstance(row[name], int | np.int64 | np.int32), row.column_names))

    new_df = pd.concat([self._data, row._data]).infer_objects()
    new_df.columns = self.column_names
    schema = Schema._merge_multiple_schemas([self.schema, row.schema])
    result = Table._from_pandas_dataframe(new_df, schema)

    for column in int_columns:
        result = result.replace_column(column, [result.get_column(column).transform(lambda it: int(it))])

    return result

add_rows(rows)

Return a new Table with multiple added Rows attached.

The order of columns of the new rows will be adjusted to the order of columns in the table. The new table will contain the merged schema.

The original table is not modified.

Parameters:

Name Type Description Default
rows list[Row] or Table

The rows to be added.

required

Returns:

Name Type Description
result Table

A new table which combines the original table and the given rows.

Raises:

Type Description
UnknownColumnNameError

If at least one of the rows have different column names than the table.

Examples:

>>> from safeds.data.tabular.containers import Row, Table
>>> table = Table.from_dict({"a": [1], "b": [2]})
>>> row1 = Row.from_dict({"a": 3, "b": 4})
>>> row2 = Row.from_dict({"a": 5, "b": 6})
>>> table.add_rows([row1, row2])
   a  b
0  1  2
1  3  4
2  5  6
Source code in src/safeds/data/tabular/containers/_table.py
def add_rows(self, rows: list[Row] | Table) -> Table:
    """
    Return a new `Table` with multiple added Rows attached.

    The order of columns of the new rows will be adjusted to the order of columns in the table.
    The new table will contain the merged schema.

    The original table is not modified.

    Parameters
    ----------
    rows : list[Row] or Table
        The rows to be added.

    Returns
    -------
    result : Table
        A new table which combines the original table and the given rows.

    Raises
    ------
    UnknownColumnNameError
        If at least one of the rows have different column names than the table.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Row, Table
    >>> table = Table.from_dict({"a": [1], "b": [2]})
    >>> row1 = Row.from_dict({"a": 3, "b": 4})
    >>> row2 = Row.from_dict({"a": 5, "b": 6})
    >>> table.add_rows([row1, row2])
       a  b
    0  1  2
    1  3  4
    2  5  6
    """
    import pandas as pd

    if isinstance(rows, Table):
        if rows.number_of_columns == 0:
            return self
        if self.number_of_columns == 0:
            return rows
        different_column_names = set(self.column_names) - set(rows.column_names)
        if len(different_column_names) > 0:
            raise UnknownColumnNameError(
                sorted(
                    different_column_names,
                    key={val: ix for ix, val in enumerate(self.column_names)}.__getitem__,
                ),
            )
        if rows.number_of_rows == 0:
            return self
        if self.number_of_rows == 0:
            return rows

        new_df = pd.concat([self._data, rows._data]).infer_objects()
        new_df.columns = self.column_names
        schema = Schema._merge_multiple_schemas([self.schema, rows.schema])
        return Table._from_pandas_dataframe(new_df, schema)

    if len(rows) == 0:
        return self

    different_column_names = set()
    for row in rows:
        different_column_names.update(set(self.column_names) - set(row.column_names))
    if len(different_column_names) > 0:
        raise UnknownColumnNameError(
            sorted(
                different_column_names,
                key={val: ix for ix, val in enumerate(self.column_names)}.__getitem__,
            ),
        )

    result = self
    for row in rows:
        result = result.add_row(row)

    return result

filter_rows(query)

Return a new table with rows filtered by Callable (e.g. lambda function).

The original table is not modified.

Parameters:

Name Type Description Default
query lambda function

A Callable that is applied to all rows.

required

Returns:

Name Type Description
table Table

A table containing only the rows filtered by the query.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
>>> table.filter_rows(lambda x: x["a"] < 2)
   a  b
0  1  2
Source code in src/safeds/data/tabular/containers/_table.py
def filter_rows(self, query: Callable[[Row], bool]) -> Table:
    """
    Return a new table with rows filtered by Callable (e.g. lambda function).

    The original table is not modified.

    Parameters
    ----------
    query : lambda function
        A Callable that is applied to all rows.

    Returns
    -------
    table : Table
        A table containing only the rows filtered by the query.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
    >>> table.filter_rows(lambda x: x["a"] < 2)
       a  b
    0  1  2
    """
    import pandas as pd

    rows: list[Row] = [row for row in self.to_rows() if query(row)]
    if len(rows) == 0:
        result_table = Table._from_pandas_dataframe(pd.DataFrame(), self._schema)
    else:
        result_table = self.from_rows(rows)
    return result_table

from_columns(columns) staticmethod

Return a table created from a list of columns.

Parameters:

Name Type Description Default
columns list[Column]

The columns to be combined. They need to have the same size.

required

Returns:

Name Type Description
table Table

The generated table.

Raises:

Type Description
ColumnLengthMismatchError

If any of the column sizes does not match with the others.

DuplicateColumnNameError

If multiple columns have the same name.

Examples:

>>> from safeds.data.tabular.containers import Column, Table
>>> col1 = Column("a", [1, 2, 3])
>>> col2 = Column("b", [4, 5, 6])
>>> Table.from_columns([col1, col2])
   a  b
0  1  4
1  2  5
2  3  6
Source code in src/safeds/data/tabular/containers/_table.py
@staticmethod
def from_columns(columns: list[Column]) -> Table:
    """
    Return a table created from a list of columns.

    Parameters
    ----------
    columns : list[Column]
        The columns to be combined. They need to have the same size.

    Returns
    -------
    table : Table
        The generated table.

    Raises
    ------
    ColumnLengthMismatchError
        If any of the column sizes does not match with the others.
    DuplicateColumnNameError
        If multiple columns have the same name.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Column, Table
    >>> col1 = Column("a", [1, 2, 3])
    >>> col2 = Column("b", [4, 5, 6])
    >>> Table.from_columns([col1, col2])
       a  b
    0  1  4
    1  2  5
    2  3  6
    """
    import pandas as pd
    from pandas import DataFrame

    dataframe: DataFrame = pd.DataFrame()
    column_names = []

    for column in columns:
        if column._data.size != columns[0]._data.size:
            raise ColumnLengthMismatchError(
                "\n".join(f"{column.name}: {column._data.size}" for column in columns),
            )
        if column.name in column_names:
            raise DuplicateColumnNameError(column.name)
        column_names.append(column.name)
        dataframe[column.name] = column._data

    return Table._from_pandas_dataframe(dataframe)

from_csv_file(path) staticmethod

Read data from a CSV file into a table.

Parameters:

Name Type Description Default
path str | Path

The path to the CSV file.

required

Returns:

Name Type Description
table Table

The table created from the CSV file.

Raises:

Type Description
FileNotFoundError

If the specified file does not exist.

WrongFileExtensionError

If the file is not a csv file.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> Table.from_csv_file('./src/resources/from_csv_file.csv')
   a  b  c
0  1  2  1
1  0  0  7
Source code in src/safeds/data/tabular/containers/_table.py
@staticmethod
def from_csv_file(path: str | Path) -> Table:
    """
    Read data from a CSV file into a table.

    Parameters
    ----------
    path : str | Path
        The path to the CSV file.

    Returns
    -------
    table : Table
        The table created from the CSV file.

    Raises
    ------
    FileNotFoundError
        If the specified file does not exist.
    WrongFileExtensionError
        If the file is not a csv file.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> Table.from_csv_file('./src/resources/from_csv_file.csv')
       a  b  c
    0  1  2  1
    1  0  0  7
    """
    import pandas as pd

    path = Path(path)
    if path.suffix != ".csv":
        raise WrongFileExtensionError(path, ".csv")
    if path.exists():
        with path.open() as f:
            if f.read().replace("\n", "") == "":
                return Table()

        return Table._from_pandas_dataframe(pd.read_csv(path))
    else:
        raise FileNotFoundError(f'File "{path}" does not exist')

from_dict(data) staticmethod

Create a table from a dictionary that maps column names to column values.

Parameters:

Name Type Description Default
data dict[str, list[Any]]

The data.

required

Returns:

Name Type Description
table Table

The generated table.

Raises:

Type Description
ColumnLengthMismatchError

If columns have different lengths.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> d = {'a': [1, 2], 'b': [3, 4]}
>>> Table.from_dict(d)
   a  b
0  1  3
1  2  4
Source code in src/safeds/data/tabular/containers/_table.py
@staticmethod
def from_dict(data: dict[str, list[Any]]) -> Table:
    """
    Create a table from a dictionary that maps column names to column values.

    Parameters
    ----------
    data : dict[str, list[Any]]
        The data.

    Returns
    -------
    table : Table
        The generated table.

    Raises
    ------
    ColumnLengthMismatchError
        If columns have different lengths.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> d = {'a': [1, 2], 'b': [3, 4]}
    >>> Table.from_dict(d)
       a  b
    0  1  3
    1  2  4
    """
    return Table(data)

from_excel_file(path) staticmethod

Read data from an Excel file into a table.

Valid file extensions are .xls, '.xlsx', .xlsm, .xlsb, .odf, .ods and .odt.

Parameters:

Name Type Description Default
path str | Path

The path to the Excel file.

required

Returns:

Name Type Description
table Table

The table created from the Excel file.

Raises:

Type Description
FileNotFoundError

If the specified file does not exist.

WrongFileExtensionError

If the file is not an Excel file.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> Table.from_excel_file('./src/resources/from_excel_file.xlsx')
   a  b
0  1  4
1  2  5
2  3  6
Source code in src/safeds/data/tabular/containers/_table.py
@staticmethod
def from_excel_file(path: str | Path) -> Table:
    """
    Read data from an Excel file into a table.

    Valid file extensions are `.xls`, '.xlsx', `.xlsm`, `.xlsb`, `.odf`, `.ods` and `.odt`.

    Parameters
    ----------
    path : str | Path
        The path to the Excel file.

    Returns
    -------
    table : Table
        The table created from the Excel file.

    Raises
    ------
    FileNotFoundError
        If the specified file does not exist.
    WrongFileExtensionError
        If the file is not an Excel file.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> Table.from_excel_file('./src/resources/from_excel_file.xlsx')
       a  b
    0  1  4
    1  2  5
    2  3  6
    """
    import pandas as pd

    path = Path(path)
    excel_extensions = [".xls", ".xlsx", ".xlsm", ".xlsb", ".odf", ".ods", ".odt"]
    if path.suffix not in excel_extensions:
        raise WrongFileExtensionError(path, excel_extensions)
    try:
        return Table._from_pandas_dataframe(
            pd.read_excel(path, engine="openpyxl", usecols=lambda colname: "Unnamed" not in colname),
        )
    except FileNotFoundError as exception:
        raise FileNotFoundError(f'File "{path}" does not exist') from exception

from_json_file(path) staticmethod

Read data from a JSON file into a table.

Parameters:

Name Type Description Default
path str | Path

The path to the JSON file.

required

Returns:

Name Type Description
table Table

The table created from the JSON file.

Raises:

Type Description
FileNotFoundError

If the specified file does not exist.

WrongFileExtensionError

If the file is not a JSON file.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> Table.from_json_file('./src/resources/from_json_file.json')
   a  b
0  1  4
1  2  5
2  3  6
Source code in src/safeds/data/tabular/containers/_table.py
@staticmethod
def from_json_file(path: str | Path) -> Table:
    """
    Read data from a JSON file into a table.

    Parameters
    ----------
    path : str | Path
        The path to the JSON file.

    Returns
    -------
    table : Table
        The table created from the JSON file.

    Raises
    ------
    FileNotFoundError
        If the specified file does not exist.
    WrongFileExtensionError
        If the file is not a JSON file.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> Table.from_json_file('./src/resources/from_json_file.json')
       a  b
    0  1  4
    1  2  5
    2  3  6
    """
    import pandas as pd

    path = Path(path)
    if path.suffix != ".json":
        raise WrongFileExtensionError(path, ".json")
    if path.exists():
        with path.open() as f:
            if f.read().replace("\n", "") in ("", "{}"):
                return Table()

        return Table._from_pandas_dataframe(pd.read_json(path))
    else:
        raise FileNotFoundError(f'File "{path}" does not exist')

from_rows(rows) staticmethod

Return a table created from a list of rows.

Parameters:

Name Type Description Default
rows list[Row]

The rows to be combined. They need to have a matching schema.

required

Returns:

Name Type Description
table Table

The generated table.

Raises:

Type Description
UnknownColumnNameError

If any of the row column names does not match with the first row.

Examples:

>>> from safeds.data.tabular.containers import Row, Table
>>> row1 = Row({"a": 1, "b": 2})
>>> row2 = Row({"a": 3, "b": 4})
>>> Table.from_rows([row1, row2])
   a  b
0  1  2
1  3  4
Source code in src/safeds/data/tabular/containers/_table.py
@staticmethod
def from_rows(rows: list[Row]) -> Table:
    """
    Return a table created from a list of rows.

    Parameters
    ----------
    rows : list[Row]
        The rows to be combined. They need to have a matching schema.

    Returns
    -------
    table : Table
        The generated table.

    Raises
    ------
    UnknownColumnNameError
        If any of the row column names does not match with the first row.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Row, Table
    >>> row1 = Row({"a": 1, "b": 2})
    >>> row2 = Row({"a": 3, "b": 4})
    >>> Table.from_rows([row1, row2])
       a  b
    0  1  2
    1  3  4
    """
    import pandas as pd
    from pandas import DataFrame

    if len(rows) == 0:
        return Table._from_pandas_dataframe(pd.DataFrame())

    column_names_compare: list = list(rows[0].column_names)
    unknown_column_names = set()
    row_array: list[pd.DataFrame] = []

    for row in rows:
        unknown_column_names.update(set(column_names_compare) - set(row.column_names))
        row_array.append(row._data)
    if len(unknown_column_names) > 0:
        raise UnknownColumnNameError(list(unknown_column_names))

    dataframe: DataFrame = pd.concat(row_array, ignore_index=True)
    dataframe.columns = column_names_compare

    schema = Schema._merge_multiple_schemas([row.schema for row in rows])

    return Table._from_pandas_dataframe(dataframe, schema)

get_column(column_name)

Return a column with the data of the specified column.

Parameters:

Name Type Description Default
column_name str

The name of the column.

required

Returns:

Name Type Description
column Column

The column.

Raises:

Type Description
UnknownColumnNameError

If the specified target column name does not exist.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table.from_dict({"a": [1], "b": [2]})
>>> table.get_column("b")
Column('b', [2])
Source code in src/safeds/data/tabular/containers/_table.py
def get_column(self, column_name: str) -> Column:
    """
    Return a column with the data of the specified column.

    Parameters
    ----------
    column_name : str
        The name of the column.

    Returns
    -------
    column : Column
        The column.

    Raises
    ------
    UnknownColumnNameError
        If the specified target column name does not exist.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table.from_dict({"a": [1], "b": [2]})
    >>> table.get_column("b")
    Column('b', [2])
    """
    if not self.has_column(column_name):
        similar_columns = self._get_similar_columns(column_name)
        raise UnknownColumnNameError([column_name], similar_columns)

    return Column._from_pandas_series(
        self._data[column_name],
        self.get_column_type(column_name),
    )

get_column_type(column_name)

Return the type of the given column.

Alias for self.schema.get_type_of_column(column_name: str) -> ColumnType.

Parameters:

Name Type Description Default
column_name str

The name of the column to be queried.

required

Returns:

Name Type Description
type ColumnType

The type of the column.

Raises:

Type Description
UnknownColumnNameError

If the specified target column name does not exist.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table.from_dict({"a": [1], "b": [2.5]})
>>> table.get_column_type("b")
RealNumber
Source code in src/safeds/data/tabular/containers/_table.py
def get_column_type(self, column_name: str) -> ColumnType:
    """
    Return the type of the given column.

    Alias for self.schema.get_type_of_column(column_name: str) -> ColumnType.

    Parameters
    ----------
    column_name : str
        The name of the column to be queried.

    Returns
    -------
    type : ColumnType
        The type of the column.

    Raises
    ------
    UnknownColumnNameError
        If the specified target column name does not exist.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table.from_dict({"a": [1], "b": [2.5]})
    >>> table.get_column_type("b")
    RealNumber
    """
    return self._schema.get_column_type(column_name)

get_row(index)

Return the row at a specified index.

Parameters:

Name Type Description Default
index int

The index.

required

Returns:

Name Type Description
row Row

The row of the table at the index.

Raises:

Type Description
IndexOutOfBoundsError

If no row at the specified index exists in this table.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
>>> table.get_row(0)
Row({
    'a': 1,
    'b': 2
})
Source code in src/safeds/data/tabular/containers/_table.py
def get_row(self, index: int) -> Row:
    """
    Return the row at a specified index.

    Parameters
    ----------
    index : int
        The index.

    Returns
    -------
    row : Row
        The row of the table at the index.

    Raises
    ------
    IndexOutOfBoundsError
        If no row at the specified index exists in this table.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
    >>> table.get_row(0)
    Row({
        'a': 1,
        'b': 2
    })
    """
    if len(self._data.index) - 1 < index or index < 0:
        raise IndexOutOfBoundsError(index)

    return Row._from_pandas_dataframe(self._data.iloc[[index]], self._schema)

group_rows_by(key_selector)

Return a dictionary with copies of the output tables as values and the keys from the key_selector.

The original table is not modified.

Parameters:

Name Type Description Default
key_selector Callable[[Row], _T]

A Callable that is applied to all rows and returns the key of the group.

required

Returns:

Name Type Description
dictionary dict

A dictionary containing the new tables as values and the selected keys as keys.

Source code in src/safeds/data/tabular/containers/_table.py
def group_rows_by(self, key_selector: Callable[[Row], _T]) -> dict[_T, Table]:
    """
    Return a dictionary with copies of the output tables as values and the keys from the key_selector.

    The original table is not modified.

    Parameters
    ----------
    key_selector : Callable[[Row], _T]
        A Callable that is applied to all rows and returns the key of the group.

    Returns
    -------
    dictionary : dict
        A dictionary containing the new tables as values and the selected keys as keys.
    """
    dictionary: dict[Table._T, Table] = {}
    for row in self.to_rows():
        if key_selector(row) in dictionary:
            dictionary[key_selector(row)] = dictionary[key_selector(row)].add_row(row)
        else:
            dictionary[key_selector(row)] = Table.from_rows([row])
    return dictionary

has_column(column_name)

Return whether the table contains a given column.

Alias for self.schema.hasColumn(column_name: str) -> bool.

Parameters:

Name Type Description Default
column_name str

The name of the column.

required

Returns:

Name Type Description
contains bool

True if the column exists.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table.from_dict({"a": [1], "b": [2]})
>>> table.has_column("b")
True
>>> table.has_column("c")
False
Source code in src/safeds/data/tabular/containers/_table.py
def has_column(self, column_name: str) -> bool:
    """
    Return whether the table contains a given column.

    Alias for self.schema.hasColumn(column_name: str) -> bool.

    Parameters
    ----------
    column_name : str
        The name of the column.

    Returns
    -------
    contains : bool
        True if the column exists.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table.from_dict({"a": [1], "b": [2]})
    >>> table.has_column("b")
    True
    >>> table.has_column("c")
    False
    """
    return self._schema.has_column(column_name)

inverse_transform_table(transformer)

Return a new Table with the inverted transformation applied by the given transformer.

The original table is not modified.

Parameters:

Name Type Description Default
transformer InvertibleTableTransformer

A transformer that was fitted with columns, which are all present in the table.

required

Returns:

Name Type Description
table Table

The original table.

Raises:

Type Description
TransformerNotFittedError

If the transformer has not been fitted yet.

Examples:

>>> from safeds.data.tabular.transformation import OneHotEncoder
>>> from safeds.data.tabular.containers import Table
>>> transformer = OneHotEncoder()
>>> table = Table.from_dict({"a": ["j", "k", "k"], "b": ["x", "y", "x"]})
>>> transformer = transformer.fit(table, None)
>>> transformed_table = transformer.transform(table)
>>> transformed_table.inverse_transform_table(transformer)
   a  b
0  j  x
1  k  y
2  k  x
>>> transformer.inverse_transform(transformed_table)
   a  b
0  j  x
1  k  y
2  k  x
Source code in src/safeds/data/tabular/containers/_table.py
def inverse_transform_table(self, transformer: InvertibleTableTransformer) -> Table:
    """
    Return a new `Table` with the inverted transformation applied by the given transformer.

    The original table is not modified.

    Parameters
    ----------
    transformer : InvertibleTableTransformer
        A transformer that was fitted with columns, which are all present in the table.

    Returns
    -------
    table : Table
        The original table.

    Raises
    ------
    TransformerNotFittedError
        If the transformer has not been fitted yet.

    Examples
    --------
    >>> from safeds.data.tabular.transformation import OneHotEncoder
    >>> from safeds.data.tabular.containers import Table
    >>> transformer = OneHotEncoder()
    >>> table = Table.from_dict({"a": ["j", "k", "k"], "b": ["x", "y", "x"]})
    >>> transformer = transformer.fit(table, None)
    >>> transformed_table = transformer.transform(table)
    >>> transformed_table.inverse_transform_table(transformer)
       a  b
    0  j  x
    1  k  y
    2  k  x
    >>> transformer.inverse_transform(transformed_table)
       a  b
    0  j  x
    1  k  y
    2  k  x
    """
    return transformer.inverse_transform(self)

keep_only_columns(column_names)

Return a new table with only the given column(s).

The original table is not modified.

Note: When removing the last column of the table, the number_of_columns property will be set to 0.

Parameters:

Name Type Description Default
column_names list[str]

A list containing only the columns to be kept.

required

Returns:

Name Type Description
table Table

A table containing only the given column(s).

Raises:

Type Description
UnknownColumnNameError

If any of the given columns does not exist.

IllegalSchemaModificationError

If removing the columns would violate an invariant in the subclass.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
>>> table.keep_only_columns(["b"])
   b
0  2
1  4
Source code in src/safeds/data/tabular/containers/_table.py
def keep_only_columns(self, column_names: list[str]) -> Table:
    """
    Return a new table with only the given column(s).

    The original table is not modified.

    Note: When removing the last column of the table, the `number_of_columns` property will be set to 0.

    Parameters
    ----------
    column_names : list[str]
        A list containing only the columns to be kept.

    Returns
    -------
    table : Table
        A table containing only the given column(s).

    Raises
    ------
    UnknownColumnNameError
        If any of the given columns does not exist.
    IllegalSchemaModificationError
        If removing the columns would violate an invariant in the subclass.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
    >>> table.keep_only_columns(["b"])
       b
    0  2
    1  4
    """
    invalid_columns = []
    similar_columns: list[str] = []
    for name in column_names:
        if not self._schema.has_column(name):
            similar_columns = similar_columns + self._get_similar_columns(name)
            invalid_columns.append(name)
    if len(invalid_columns) != 0:
        raise UnknownColumnNameError(invalid_columns, similar_columns)

    return self.remove_columns(list(set(self.column_names) - set(column_names)))

plot_boxplots()

Plot a boxplot for every numerical column.

Returns:

Name Type Description
plot Image

The plot as an image.

Raises:

Type Description
NonNumericColumnError

If the table contains only non-numerical columns.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table({"a":[1, 2], "b": [3, 42]})
>>> image = table.plot_boxplots()
Source code in src/safeds/data/tabular/containers/_table.py
def plot_boxplots(self) -> Image:
    """
    Plot a boxplot for every numerical column.

    Returns
    -------
    plot: Image
        The plot as an image.

    Raises
    ------
    NonNumericColumnError
        If the table contains only non-numerical columns.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table({"a":[1, 2], "b": [3, 42]})
    >>> image = table.plot_boxplots()
    """
    import matplotlib.pyplot as plt
    import pandas as pd
    import seaborn as sns

    numerical_table = self.remove_columns_with_non_numerical_values()
    if numerical_table.number_of_columns == 0:
        raise NonNumericColumnError("This table contains only non-numerical columns.")
    col_wrap = min(numerical_table.number_of_columns, 3)

    data = pd.melt(numerical_table._data, value_vars=numerical_table.column_names)
    grid = sns.FacetGrid(data, col="variable", col_wrap=col_wrap, sharex=False, sharey=False)
    with warnings.catch_warnings():
        warnings.filterwarnings(
            "ignore",
            message="Using the boxplot function without specifying `order` is likely to produce an incorrect plot.",
        )
        grid.map(sns.boxplot, "variable", "value")
    grid.set_xlabels("")
    grid.set_ylabels("")
    grid.set_titles("{col_name}")
    for axes in grid.axes.flat:
        axes.set_xticks([])
    plt.tight_layout()
    fig = grid.fig

    buffer = io.BytesIO()
    fig.savefig(buffer, format="png")
    plt.close()  # Prevents the figure from being displayed directly
    buffer.seek(0)
    return Image.from_bytes(buffer.read())

plot_correlation_heatmap()

Plot a correlation heatmap for all numerical columns of this Table.

Returns:

Name Type Description
plot Image

The plot as an image.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table.from_dict({"temperature": [10, 15, 20, 25, 30], "sales": [54, 74, 90, 206, 210]})
>>> image = table.plot_correlation_heatmap()
Source code in src/safeds/data/tabular/containers/_table.py
def plot_correlation_heatmap(self) -> Image:
    """
    Plot a correlation heatmap for all numerical columns of this `Table`.

    Returns
    -------
    plot: Image
        The plot as an image.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table.from_dict({"temperature": [10, 15, 20, 25, 30], "sales": [54, 74, 90, 206, 210]})
    >>> image = table.plot_correlation_heatmap()
    """
    import matplotlib.pyplot as plt
    import seaborn as sns

    only_numerical = self.remove_columns_with_non_numerical_values()

    if self.number_of_rows == 0:
        warnings.warn(
            "An empty table has been used. A correlation heatmap on an empty table will show nothing.",
            stacklevel=2,
        )

        with warnings.catch_warnings():
            warnings.filterwarnings(
                "ignore",
                message=(
                    "Attempting to set identical low and high (xlims|ylims) makes transformation singular;"
                    " automatically expanding."
                ),
            )
            fig = plt.figure()
            sns.heatmap(
                data=only_numerical._data.corr(),
                vmin=-1,
                vmax=1,
                xticklabels=only_numerical.column_names,
                yticklabels=only_numerical.column_names,
                cmap="vlag",
            )
            plt.tight_layout()
    else:
        fig = plt.figure()
        sns.heatmap(
            data=only_numerical._data.corr(),
            vmin=-1,
            vmax=1,
            xticklabels=only_numerical.column_names,
            yticklabels=only_numerical.column_names,
            cmap="vlag",
        )
        plt.tight_layout()

    buffer = io.BytesIO()
    fig.savefig(buffer, format="png")
    plt.close()  # Prevents the figure from being displayed directly
    buffer.seek(0)
    return Image.from_bytes(buffer.read())

plot_histograms()

Plot a histogram for every column.

Returns:

Name Type Description
plot Image

The plot as an image.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table({"a": [2, 3, 5, 1], "b": [54, 74, 90, 2014]})
>>> image = table.plot_histograms()
Source code in src/safeds/data/tabular/containers/_table.py
def plot_histograms(self) -> Image:
    """
    Plot a histogram for every column.

    Returns
    -------
    plot: Image
        The plot as an image.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table({"a": [2, 3, 5, 1], "b": [54, 74, 90, 2014]})
    >>> image = table.plot_histograms()
    """
    import matplotlib.pyplot as plt
    import pandas as pd
    import seaborn as sns

    col_wrap = min(self.number_of_columns, 3)

    data = pd.melt(self._data.map(lambda value: str(value)), value_vars=self.column_names)
    grid = sns.FacetGrid(data=data, col="variable", col_wrap=col_wrap, sharex=False, sharey=False)
    grid.map(sns.histplot, "value")
    grid.set_xlabels("")
    grid.set_ylabels("")
    grid.set_titles("{col_name}")
    for axes in grid.axes.flat:
        axes.set_xticks(axes.get_xticks())
        axes.set_xticklabels(axes.get_xticklabels(), rotation=45, horizontalalignment="right")
    grid.tight_layout()
    fig = grid.fig

    buffer = io.BytesIO()
    fig.savefig(buffer, format="png")
    plt.close()
    buffer.seek(0)
    return Image.from_bytes(buffer.read())

plot_lineplot(x_column_name, y_column_name)

Plot two columns against each other in a lineplot.

If there are multiple x-values for a y-value, the resulting plot will consist of a line representing the mean and the lower-transparency area around the line representing the 95% confidence interval.

Parameters:

Name Type Description Default
x_column_name str

The column name of the column to be plotted on the x-Axis.

required
y_column_name str

The column name of the column to be plotted on the y-Axis.

required

Returns:

Name Type Description
plot Image

The plot as an image.

Raises:

Type Description
UnknownColumnNameError

If either of the columns do not exist.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table.from_dict({"temperature": [10, 15, 20, 25, 30], "sales": [54, 74, 90, 206, 210]})
>>> image = table.plot_lineplot("temperature", "sales")
Source code in src/safeds/data/tabular/containers/_table.py
def plot_lineplot(self, x_column_name: str, y_column_name: str) -> Image:
    """
    Plot two columns against each other in a lineplot.

    If there are multiple x-values for a y-value, the resulting plot will consist of a line representing the mean
    and the lower-transparency area around the line representing the 95% confidence interval.

    Parameters
    ----------
    x_column_name : str
        The column name of the column to be plotted on the x-Axis.
    y_column_name : str
        The column name of the column to be plotted on the y-Axis.

    Returns
    -------
    plot: Image
        The plot as an image.

    Raises
    ------
    UnknownColumnNameError
        If either of the columns do not exist.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table.from_dict({"temperature": [10, 15, 20, 25, 30], "sales": [54, 74, 90, 206, 210]})
    >>> image = table.plot_lineplot("temperature", "sales")
    """
    import matplotlib.pyplot as plt
    import seaborn as sns

    if not self.has_column(x_column_name) or not self.has_column(y_column_name):
        similar_columns_x = self._get_similar_columns(x_column_name)
        similar_columns_y = self._get_similar_columns(y_column_name)
        raise UnknownColumnNameError(
            ([x_column_name] if not self.has_column(x_column_name) else [])
            + ([y_column_name] if not self.has_column(y_column_name) else []),
            (similar_columns_x if not self.has_column(x_column_name) else [])
            + (similar_columns_y if not self.has_column(y_column_name) else []),
        )

    fig = plt.figure()
    ax = sns.lineplot(
        data=self._data,
        x=x_column_name,
        y=y_column_name,
    )
    ax.set(xlabel=x_column_name, ylabel=y_column_name)
    ax.set_xticks(ax.get_xticks())
    ax.set_xticklabels(
        ax.get_xticklabels(),
        rotation=45,
        horizontalalignment="right",
    )  # rotate the labels of the x Axis to prevent the chance of overlapping of the labels
    plt.tight_layout()

    buffer = io.BytesIO()
    fig.savefig(buffer, format="png")
    plt.close()  # Prevents the figure from being displayed directly
    buffer.seek(0)
    return Image.from_bytes(buffer.read())

plot_scatterplot(x_column_name, y_column_name)

Plot two columns against each other in a scatterplot.

Parameters:

Name Type Description Default
x_column_name str

The column name of the column to be plotted on the x-Axis.

required
y_column_name str

The column name of the column to be plotted on the y-Axis.

required

Returns:

Name Type Description
plot Image

The plot as an image.

Raises:

Type Description
UnknownColumnNameError

If either of the columns do not exist.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table.from_dict({"temperature": [10, 15, 20, 25, 30], "sales": [54, 74, 90, 206, 210]})
>>> image = table.plot_scatterplot("temperature", "sales")
Source code in src/safeds/data/tabular/containers/_table.py
def plot_scatterplot(self, x_column_name: str, y_column_name: str) -> Image:
    """
    Plot two columns against each other in a scatterplot.

    Parameters
    ----------
    x_column_name : str
        The column name of the column to be plotted on the x-Axis.
    y_column_name : str
        The column name of the column to be plotted on the y-Axis.

    Returns
    -------
    plot: Image
        The plot as an image.

    Raises
    ------
    UnknownColumnNameError
        If either of the columns do not exist.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table.from_dict({"temperature": [10, 15, 20, 25, 30], "sales": [54, 74, 90, 206, 210]})
    >>> image = table.plot_scatterplot("temperature", "sales")
    """
    import matplotlib.pyplot as plt
    import seaborn as sns

    if not self.has_column(x_column_name) or not self.has_column(y_column_name):
        similar_columns_x = self._get_similar_columns(x_column_name)
        similar_columns_y = self._get_similar_columns(y_column_name)
        raise UnknownColumnNameError(
            ([x_column_name] if not self.has_column(x_column_name) else [])
            + ([y_column_name] if not self.has_column(y_column_name) else []),
            (similar_columns_x if not self.has_column(x_column_name) else [])
            + (similar_columns_y if not self.has_column(y_column_name) else []),
        )

    fig = plt.figure()
    ax = sns.scatterplot(
        data=self._data,
        x=x_column_name,
        y=y_column_name,
    )
    ax.set(xlabel=x_column_name, ylabel=y_column_name)
    ax.set_xticks(ax.get_xticks())
    ax.set_xticklabels(
        ax.get_xticklabels(),
        rotation=45,
        horizontalalignment="right",
    )  # rotate the labels of the x Axis to prevent the chance of overlapping of the labels
    plt.tight_layout()

    buffer = io.BytesIO()
    fig.savefig(buffer, format="png")
    plt.close()  # Prevents the figure from being displayed directly
    buffer.seek(0)
    return Image.from_bytes(buffer.read())

remove_columns(column_names)

Return a new table without the given column(s).

The original table is not modified.

Note: When removing the last column of the table, the number_of_columns property will be set to 0.

Parameters:

Name Type Description Default
column_names list[str]

A list containing all columns to be dropped.

required

Returns:

Name Type Description
table Table

A table without the given columns.

Raises:

Type Description
UnknownColumnNameError

If any of the given columns does not exist.

IllegalSchemaModificationError

If removing the columns would violate an invariant in the subclass.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
>>> table.remove_columns(["b"])
   a
0  1
1  3
Source code in src/safeds/data/tabular/containers/_table.py
def remove_columns(self, column_names: list[str]) -> Table:
    """
    Return a new table without the given column(s).

    The original table is not modified.

    Note: When removing the last column of the table, the `number_of_columns` property will be set to 0.

    Parameters
    ----------
    column_names : list[str]
        A list containing all columns to be dropped.

    Returns
    -------
    table : Table
        A table without the given columns.

    Raises
    ------
    UnknownColumnNameError
        If any of the given columns does not exist.
    IllegalSchemaModificationError
        If removing the columns would violate an invariant in the subclass.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table.from_dict({"a": [1, 3], "b": [2, 4]})
    >>> table.remove_columns(["b"])
       a
    0  1
    1  3
    """
    invalid_columns = []
    similar_columns: list[str] = []
    for name in column_names:
        if not self._schema.has_column(name):
            similar_columns = similar_columns + self._get_similar_columns(name)
            invalid_columns.append(name)
    if len(invalid_columns) != 0:
        raise UnknownColumnNameError(invalid_columns, similar_columns)

    transformed_data = self._data.drop(labels=column_names, axis="columns")
    transformed_data.columns = [name for name in self._schema.column_names if name not in column_names]

    if len(transformed_data.columns) == 0:
        return Table()

    return Table._from_pandas_dataframe(transformed_data)

remove_columns_with_missing_values()

Return a new table without the columns that contain missing values.

The original table is not modified.

Note: When removing the last column of the table, the number_of_columns property will be set to 0.

Returns:

Name Type Description
table Table

A table without the columns that contain missing values.

Raises:

Type Description
IllegalSchemaModificationError

If removing the columns would violate an invariant in the subclass.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table.from_dict({"a": [1, 2], "b": [None, 2]})
>>> table.remove_columns_with_missing_values()
   a
0  1
1  2
Source code in src/safeds/data/tabular/containers/_table.py
def remove_columns_with_missing_values(self) -> Table:
    """
    Return a new table without the columns that contain missing values.

    The original table is not modified.

    Note: When removing the last column of the table, the `number_of_columns` property will be set to 0.

    Returns
    -------
    table : Table
        A table without the columns that contain missing values.

    Raises
    ------
    IllegalSchemaModificationError
        If removing the columns would violate an invariant in the subclass.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table.from_dict({"a": [1, 2], "b": [None, 2]})
    >>> table.remove_columns_with_missing_values()
       a
    0  1
    1  2
    """
    return Table.from_columns([column for column in self.to_columns() if not column.has_missing_values()])

remove_columns_with_non_numerical_values()

Return a new table without the columns that contain non-numerical values.

The original table is not modified.

Note: When removing the last column of the table, the number_of_columns property will be set to 0.

Returns:

Name Type Description
table Table

A table without the columns that contain non-numerical values.

Raises:

Type Description
IllegalSchemaModificationError

If removing the columns would violate an invariant in the subclass.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table.from_dict({"a": [1, 0], "b": ["test", 2]})
>>> table.remove_columns_with_non_numerical_values()
   a
0  1
1  0
Source code in src/safeds/data/tabular/containers/_table.py