File size: 207,873 Bytes
9c6594c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from cpython.pycapsule cimport PyCapsule_CheckExact, PyCapsule_GetPointer, PyCapsule_New
import warnings
from cython import sizeof
cdef class ChunkedArray(_PandasConvertible):
"""
An array-like composed from a (possibly empty) collection of pyarrow.Arrays
Warnings
--------
Do not call this class's constructor directly.
Examples
--------
To construct a ChunkedArray object use :func:`pyarrow.chunked_array`:
>>> import pyarrow as pa
>>> pa.chunked_array([], type=pa.int8())
<pyarrow.lib.ChunkedArray object at ...>
[
...
]
>>> pa.chunked_array([[2, 2, 4], [4, 5, 100]])
<pyarrow.lib.ChunkedArray object at ...>
[
[
2,
2,
4
],
[
4,
5,
100
]
]
>>> isinstance(pa.chunked_array([[2, 2, 4], [4, 5, 100]]), pa.ChunkedArray)
True
"""
def __cinit__(self):
self.chunked_array = NULL
self._init_is_cpu = False
def __init__(self):
raise TypeError("Do not call ChunkedArray's constructor directly, use "
"`chunked_array` function instead.")
cdef void init(self, const shared_ptr[CChunkedArray]& chunked_array):
self.sp_chunked_array = chunked_array
self.chunked_array = chunked_array.get()
def __reduce__(self):
self._assert_cpu()
return chunked_array, (self.chunks, self.type)
@property
def data(self):
import warnings
warnings.warn("Calling .data on ChunkedArray is provided for "
"compatibility after Column was removed, simply drop "
"this attribute", FutureWarning)
return self
@property
def type(self):
"""
Return data type of a ChunkedArray.
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, 5, 100]])
>>> n_legs.type
DataType(int64)
"""
return pyarrow_wrap_data_type(self.sp_chunked_array.get().type())
def length(self):
"""
Return length of a ChunkedArray.
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, 5, 100]])
>>> n_legs.length()
6
"""
return self.chunked_array.length()
def __len__(self):
return self.length()
def __repr__(self):
type_format = object.__repr__(self)
return '{0}\n{1}'.format(type_format, str(self))
def to_string(self, *, int indent=0, int window=5, int container_window=2,
c_bool skip_new_lines=False):
"""
Render a "pretty-printed" string representation of the ChunkedArray
Parameters
----------
indent : int
How much to indent right the content of the array,
by default ``0``.
window : int
How many items to preview within each chunk at the begin and end
of the chunk when the chunk is bigger than the window.
The other elements will be ellipsed.
container_window : int
How many chunks to preview at the begin and end
of the array when the array is bigger than the window.
The other elements will be ellipsed.
This setting also applies to list columns.
skip_new_lines : bool
If the array should be rendered as a single line of text
or if each element should be on its own line.
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, 5, 100]])
>>> n_legs.to_string(skip_new_lines=True)
'[[2,2,4],[4,5,100]]'
"""
cdef:
c_string result
PrettyPrintOptions options
with nogil:
options = PrettyPrintOptions(indent, window)
options.skip_new_lines = skip_new_lines
options.container_window = container_window
check_status(
PrettyPrint(
deref(self.chunked_array),
options,
&result
)
)
return frombytes(result, safe=True)
def format(self, **kwargs):
"""
DEPRECATED, use pyarrow.ChunkedArray.to_string
Parameters
----------
**kwargs : dict
Returns
-------
str
"""
import warnings
warnings.warn('ChunkedArray.format is deprecated, '
'use ChunkedArray.to_string')
return self.to_string(**kwargs)
def __str__(self):
return self.to_string()
def validate(self, *, full=False):
"""
Perform validation checks. An exception is raised if validation fails.
By default only cheap validation checks are run. Pass `full=True`
for thorough validation checks (potentially O(n)).
Parameters
----------
full : bool, default False
If True, run expensive checks, otherwise cheap checks only.
Raises
------
ArrowInvalid
"""
if full:
self._assert_cpu()
with nogil:
check_status(self.sp_chunked_array.get().ValidateFull())
else:
with nogil:
check_status(self.sp_chunked_array.get().Validate())
@property
def null_count(self):
"""
Number of null entries
Returns
-------
int
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, None, 100]])
>>> n_legs.null_count
1
"""
self._assert_cpu()
return self.chunked_array.null_count()
@property
def nbytes(self):
"""
Total number of bytes consumed by the elements of the chunked array.
In other words, the sum of bytes from all buffer ranges referenced.
Unlike `get_total_buffer_size` this method will account for array
offsets.
If buffers are shared between arrays then the shared
portion will only be counted multiple times.
The dictionary of dictionary arrays will always be counted in their
entirety even if the array only references a portion of the dictionary.
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, None, 100]])
>>> n_legs.nbytes
49
"""
self._assert_cpu()
cdef:
CResult[int64_t] c_res_buffer
with nogil:
c_res_buffer = ReferencedBufferSize(deref(self.chunked_array))
size = GetResultValue(c_res_buffer)
return size
def get_total_buffer_size(self):
"""
The sum of bytes in each buffer referenced by the chunked array.
An array may only reference a portion of a buffer.
This method will overestimate in this case and return the
byte size of the entire buffer.
If a buffer is referenced multiple times then it will
only be counted once.
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, None, 100]])
>>> n_legs.get_total_buffer_size()
49
"""
self._assert_cpu()
cdef:
int64_t total_buffer_size
total_buffer_size = TotalBufferSize(deref(self.chunked_array))
return total_buffer_size
def __sizeof__(self):
return super(ChunkedArray, self).__sizeof__() + self.nbytes
def __iter__(self):
for chunk in self.iterchunks():
for item in chunk:
yield item
def __getitem__(self, key):
"""
Slice or return value at given index
Parameters
----------
key : integer or slice
Slices with step not equal to 1 (or None) will produce a copy
rather than a zero-copy view
Returns
-------
value : Scalar (index) or ChunkedArray (slice)
"""
self._assert_cpu()
if isinstance(key, slice):
return _normalize_slice(self, key)
return self.getitem(_normalize_index(key, self.chunked_array.length()))
cdef getitem(self, int64_t i):
self._assert_cpu()
return Scalar.wrap(GetResultValue(self.chunked_array.GetScalar(i)))
def is_null(self, *, nan_is_null=False):
"""
Return boolean array indicating the null values.
Parameters
----------
nan_is_null : bool (optional, default False)
Whether floating-point NaN values should also be considered null.
Returns
-------
array : boolean Array or ChunkedArray
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, None, 100]])
>>> n_legs.is_null()
<pyarrow.lib.ChunkedArray object at ...>
[
[
false,
false,
false,
false,
true,
false
]
]
"""
self._assert_cpu()
options = _pc().NullOptions(nan_is_null=nan_is_null)
return _pc().call_function('is_null', [self], options)
def is_nan(self):
"""
Return boolean array indicating the NaN values.
Examples
--------
>>> import pyarrow as pa
>>> import numpy as np
>>> arr = pa.chunked_array([[2, np.nan, 4], [4, None, 100]])
>>> arr.is_nan()
<pyarrow.lib.ChunkedArray object at ...>
[
[
false,
true,
false,
false,
null,
false
]
]
"""
self._assert_cpu()
return _pc().is_nan(self)
def is_valid(self):
"""
Return boolean array indicating the non-null values.
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, None, 100]])
>>> n_legs.is_valid()
<pyarrow.lib.ChunkedArray object at ...>
[
[
true,
true,
true
],
[
true,
false,
true
]
]
"""
self._assert_cpu()
return _pc().is_valid(self)
def __eq__(self, other):
try:
return self.equals(other)
except TypeError:
return NotImplemented
def fill_null(self, fill_value):
"""
Replace each null element in values with fill_value.
See :func:`pyarrow.compute.fill_null` for full usage.
Parameters
----------
fill_value : any
The replacement value for null entries.
Returns
-------
result : Array or ChunkedArray
A new array with nulls replaced by the given value.
Examples
--------
>>> import pyarrow as pa
>>> fill_value = pa.scalar(5, type=pa.int8())
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, None, 100]])
>>> n_legs.fill_null(fill_value)
<pyarrow.lib.ChunkedArray object at ...>
[
[
2,
2,
4,
4,
5,
100
]
]
"""
self._assert_cpu()
return _pc().fill_null(self, fill_value)
def equals(self, ChunkedArray other):
"""
Return whether the contents of two chunked arrays are equal.
Parameters
----------
other : pyarrow.ChunkedArray
Chunked array to compare against.
Returns
-------
are_equal : bool
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, 5, 100]])
>>> animals = pa.chunked_array((
... ["Flamingo", "Parrot", "Dog"],
... ["Horse", "Brittle stars", "Centipede"]
... ))
>>> n_legs.equals(n_legs)
True
>>> n_legs.equals(animals)
False
"""
self._assert_cpu()
if other is None:
return False
cdef:
CChunkedArray* this_arr = self.chunked_array
CChunkedArray* other_arr = other.chunked_array
c_bool result
with nogil:
result = this_arr.Equals(deref(other_arr))
return result
def _to_pandas(self, options, types_mapper=None, **kwargs):
self._assert_cpu()
return _array_like_to_pandas(self, options, types_mapper=types_mapper)
def to_numpy(self, zero_copy_only=False):
"""
Return a NumPy copy of this array (experimental).
Parameters
----------
zero_copy_only : bool, default False
Introduced for signature consistence with pyarrow.Array.to_numpy.
This must be False here since NumPy arrays' buffer must be contiguous.
Returns
-------
array : numpy.ndarray
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, 5, 100]])
>>> n_legs.to_numpy()
array([ 2, 2, 4, 4, 5, 100])
"""
self._assert_cpu()
if np is None:
raise ImportError(
"Cannot return a numpy.ndarray if NumPy is not present")
if zero_copy_only:
raise ValueError(
"zero_copy_only must be False for pyarrow.ChunkedArray.to_numpy"
)
cdef:
PyObject* out
PandasOptions c_options
object values
c_options.to_numpy = True
with nogil:
check_status(
ConvertChunkedArrayToPandas(
c_options,
self.sp_chunked_array,
self,
&out
)
)
# wrap_array_output uses pandas to convert to Categorical, here
# always convert to numpy array
values = PyObject_to_object(out)
if isinstance(values, dict):
values = np.take(values['dictionary'], values['indices'])
return values
def __array__(self, dtype=None, copy=None):
self._assert_cpu()
if copy is False:
raise ValueError(
"Unable to avoid a copy while creating a numpy array as requested "
"(converting a pyarrow.ChunkedArray always results in a copy).\n"
"If using `np.array(obj, copy=False)` replace it with "
"`np.asarray(obj)` to allow a copy when needed"
)
# 'copy' can further be ignored because to_numpy() already returns a copy
values = self.to_numpy()
if dtype is None:
return values
return values.astype(dtype, copy=False)
def cast(self, object target_type=None, safe=None, options=None):
"""
Cast array values to another data type
See :func:`pyarrow.compute.cast` for usage.
Parameters
----------
target_type : DataType, None
Type to cast array to.
safe : boolean, default True
Whether to check for conversion errors such as overflow.
options : CastOptions, default None
Additional checks pass by CastOptions
Returns
-------
cast : Array or ChunkedArray
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, 5, 100]])
>>> n_legs.type
DataType(int64)
Change the data type of an array:
>>> n_legs_seconds = n_legs.cast(pa.duration('s'))
>>> n_legs_seconds.type
DurationType(duration[s])
"""
self._assert_cpu()
return _pc().cast(self, target_type, safe=safe, options=options)
def dictionary_encode(self, null_encoding='mask'):
"""
Compute dictionary-encoded representation of array.
See :func:`pyarrow.compute.dictionary_encode` for full usage.
Parameters
----------
null_encoding : str, default "mask"
How to handle null entries.
Returns
-------
encoded : ChunkedArray
A dictionary-encoded version of this array.
Examples
--------
>>> import pyarrow as pa
>>> animals = pa.chunked_array((
... ["Flamingo", "Parrot", "Dog"],
... ["Horse", "Brittle stars", "Centipede"]
... ))
>>> animals.dictionary_encode()
<pyarrow.lib.ChunkedArray object at ...>
[
...
-- dictionary:
[
"Flamingo",
"Parrot",
"Dog",
"Horse",
"Brittle stars",
"Centipede"
]
-- indices:
[
0,
1,
2
],
...
-- dictionary:
[
"Flamingo",
"Parrot",
"Dog",
"Horse",
"Brittle stars",
"Centipede"
]
-- indices:
[
3,
4,
5
]
]
"""
self._assert_cpu()
options = _pc().DictionaryEncodeOptions(null_encoding)
return _pc().call_function('dictionary_encode', [self], options)
def flatten(self, MemoryPool memory_pool=None):
"""
Flatten this ChunkedArray. If it has a struct type, the column is
flattened into one array per struct field.
Parameters
----------
memory_pool : MemoryPool, default None
For memory allocations, if required, otherwise use default pool
Returns
-------
result : list of ChunkedArray
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, 5, 100]])
>>> c_arr = pa.chunked_array(n_legs.value_counts())
>>> c_arr
<pyarrow.lib.ChunkedArray object at ...>
[
-- is_valid: all not null
-- child 0 type: int64
[
2,
4,
5,
100
]
-- child 1 type: int64
[
2,
2,
1,
1
]
]
>>> c_arr.flatten()
[<pyarrow.lib.ChunkedArray object at ...>
[
[
2,
4,
5,
100
]
], <pyarrow.lib.ChunkedArray object at ...>
[
[
2,
2,
1,
1
]
]]
>>> c_arr.type
StructType(struct<values: int64, counts: int64>)
>>> n_legs.type
DataType(int64)
"""
self._assert_cpu()
cdef:
vector[shared_ptr[CChunkedArray]] flattened
CMemoryPool* pool = maybe_unbox_memory_pool(memory_pool)
with nogil:
flattened = GetResultValue(self.chunked_array.Flatten(pool))
return [pyarrow_wrap_chunked_array(col) for col in flattened]
def combine_chunks(self, MemoryPool memory_pool=None):
"""
Flatten this ChunkedArray into a single non-chunked array.
Parameters
----------
memory_pool : MemoryPool, default None
For memory allocations, if required, otherwise use default pool
Returns
-------
result : Array
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, 5, 100]])
>>> n_legs
<pyarrow.lib.ChunkedArray object at ...>
[
[
2,
2,
4
],
[
4,
5,
100
]
]
>>> n_legs.combine_chunks()
<pyarrow.lib.Int64Array object at ...>
[
2,
2,
4,
4,
5,
100
]
"""
self._assert_cpu()
if self.num_chunks == 0:
return array([], type=self.type)
else:
return concat_arrays(self.chunks)
def unique(self):
"""
Compute distinct elements in array
Returns
-------
pyarrow.Array
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, 5, 100]])
>>> n_legs
<pyarrow.lib.ChunkedArray object at ...>
[
[
2,
2,
4
],
[
4,
5,
100
]
]
>>> n_legs.unique()
<pyarrow.lib.Int64Array object at ...>
[
2,
4,
5,
100
]
"""
self._assert_cpu()
return _pc().call_function('unique', [self])
def value_counts(self):
"""
Compute counts of unique elements in array.
Returns
-------
An array of <input type "Values", int64_t "Counts"> structs
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, 5, 100]])
>>> n_legs
<pyarrow.lib.ChunkedArray object at ...>
[
[
2,
2,
4
],
[
4,
5,
100
]
]
>>> n_legs.value_counts()
<pyarrow.lib.StructArray object at ...>
-- is_valid: all not null
-- child 0 type: int64
[
2,
4,
5,
100
]
-- child 1 type: int64
[
2,
2,
1,
1
]
"""
self._assert_cpu()
return _pc().call_function('value_counts', [self])
def slice(self, offset=0, length=None):
"""
Compute zero-copy slice of this ChunkedArray
Parameters
----------
offset : int, default 0
Offset from start of array to slice
length : int, default None
Length of slice (default is until end of batch starting from
offset)
Returns
-------
sliced : ChunkedArray
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, 5, 100]])
>>> n_legs
<pyarrow.lib.ChunkedArray object at ...>
[
[
2,
2,
4
],
[
4,
5,
100
]
]
>>> n_legs.slice(2,2)
<pyarrow.lib.ChunkedArray object at ...>
[
[
4
],
[
4
]
]
"""
cdef shared_ptr[CChunkedArray] result
if offset < 0:
raise IndexError('Offset must be non-negative')
offset = min(len(self), offset)
if length is None:
result = self.chunked_array.Slice(offset)
else:
result = self.chunked_array.Slice(offset, length)
return pyarrow_wrap_chunked_array(result)
def filter(self, mask, object null_selection_behavior="drop"):
"""
Select values from the chunked array.
See :func:`pyarrow.compute.filter` for full usage.
Parameters
----------
mask : Array or array-like
The boolean mask to filter the chunked array with.
null_selection_behavior : str, default "drop"
How nulls in the mask should be handled.
Returns
-------
filtered : Array or ChunkedArray
An array of the same type, with only the elements selected by
the boolean mask.
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, 5, 100]])
>>> n_legs
<pyarrow.lib.ChunkedArray object at ...>
[
[
2,
2,
4
],
[
4,
5,
100
]
]
>>> mask = pa.array([True, False, None, True, False, True])
>>> n_legs.filter(mask)
<pyarrow.lib.ChunkedArray object at ...>
[
[
2
],
[
4,
100
]
]
>>> n_legs.filter(mask, null_selection_behavior="emit_null")
<pyarrow.lib.ChunkedArray object at ...>
[
[
2,
null
],
[
4,
100
]
]
"""
self._assert_cpu()
return _pc().filter(self, mask, null_selection_behavior)
def index(self, value, start=None, end=None, *, memory_pool=None):
"""
Find the first index of a value.
See :func:`pyarrow.compute.index` for full usage.
Parameters
----------
value : Scalar or object
The value to look for in the array.
start : int, optional
The start index where to look for `value`.
end : int, optional
The end index where to look for `value`.
memory_pool : MemoryPool, optional
A memory pool for potential memory allocations.
Returns
-------
index : Int64Scalar
The index of the value in the array (-1 if not found).
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, 5, 100]])
>>> n_legs
<pyarrow.lib.ChunkedArray object at ...>
[
[
2,
2,
4
],
[
4,
5,
100
]
]
>>> n_legs.index(4)
<pyarrow.Int64Scalar: 2>
>>> n_legs.index(4, start=3)
<pyarrow.Int64Scalar: 3>
"""
self._assert_cpu()
return _pc().index(self, value, start, end, memory_pool=memory_pool)
def take(self, object indices):
"""
Select values from the chunked array.
See :func:`pyarrow.compute.take` for full usage.
Parameters
----------
indices : Array or array-like
The indices in the array whose values will be returned.
Returns
-------
taken : Array or ChunkedArray
An array with the same datatype, containing the taken values.
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, 5, 100]])
>>> n_legs
<pyarrow.lib.ChunkedArray object at ...>
[
[
2,
2,
4
],
[
4,
5,
100
]
]
>>> n_legs.take([1,4,5])
<pyarrow.lib.ChunkedArray object at ...>
[
[
2,
5,
100
]
]
"""
self._assert_cpu()
return _pc().take(self, indices)
def drop_null(self):
"""
Remove missing values from a chunked array.
See :func:`pyarrow.compute.drop_null` for full description.
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, None], [4, 5, 100]])
>>> n_legs
<pyarrow.lib.ChunkedArray object at ...>
[
[
2,
2,
null
],
[
4,
5,
100
]
]
>>> n_legs.drop_null()
<pyarrow.lib.ChunkedArray object at ...>
[
[
2,
2
],
[
4,
5,
100
]
]
"""
self._assert_cpu()
return _pc().drop_null(self)
def sort(self, order="ascending", **kwargs):
"""
Sort the ChunkedArray
Parameters
----------
order : str, default "ascending"
Which order to sort values in.
Accepted values are "ascending", "descending".
**kwargs : dict, optional
Additional sorting options.
As allowed by :class:`SortOptions`
Returns
-------
result : ChunkedArray
"""
self._assert_cpu()
indices = _pc().sort_indices(
self,
options=_pc().SortOptions(sort_keys=[("", order)], **kwargs)
)
return self.take(indices)
def unify_dictionaries(self, MemoryPool memory_pool=None):
"""
Unify dictionaries across all chunks.
This method returns an equivalent chunked array, but where all
chunks share the same dictionary values. Dictionary indices are
transposed accordingly.
If there are no dictionaries in the chunked array, it is returned
unchanged.
Parameters
----------
memory_pool : MemoryPool, default None
For memory allocations, if required, otherwise use default pool
Returns
-------
result : ChunkedArray
Examples
--------
>>> import pyarrow as pa
>>> arr_1 = pa.array(["Flamingo", "Parrot", "Dog"]).dictionary_encode()
>>> arr_2 = pa.array(["Horse", "Brittle stars", "Centipede"]).dictionary_encode()
>>> c_arr = pa.chunked_array([arr_1, arr_2])
>>> c_arr
<pyarrow.lib.ChunkedArray object at ...>
[
...
-- dictionary:
[
"Flamingo",
"Parrot",
"Dog"
]
-- indices:
[
0,
1,
2
],
...
-- dictionary:
[
"Horse",
"Brittle stars",
"Centipede"
]
-- indices:
[
0,
1,
2
]
]
>>> c_arr.unify_dictionaries()
<pyarrow.lib.ChunkedArray object at ...>
[
...
-- dictionary:
[
"Flamingo",
"Parrot",
"Dog",
"Horse",
"Brittle stars",
"Centipede"
]
-- indices:
[
0,
1,
2
],
...
-- dictionary:
[
"Flamingo",
"Parrot",
"Dog",
"Horse",
"Brittle stars",
"Centipede"
]
-- indices:
[
3,
4,
5
]
]
"""
self._assert_cpu()
cdef:
CMemoryPool* pool = maybe_unbox_memory_pool(memory_pool)
shared_ptr[CChunkedArray] c_result
with nogil:
c_result = GetResultValue(CDictionaryUnifier.UnifyChunkedArray(
self.sp_chunked_array, pool))
return pyarrow_wrap_chunked_array(c_result)
@property
def num_chunks(self):
"""
Number of underlying chunks.
Returns
-------
int
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, None], [4, 5, 100]])
>>> n_legs.num_chunks
2
"""
return self.chunked_array.num_chunks()
def chunk(self, i):
"""
Select a chunk by its index.
Parameters
----------
i : int
Returns
-------
pyarrow.Array
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, None], [4, 5, 100]])
>>> n_legs.chunk(1)
<pyarrow.lib.Int64Array object at ...>
[
4,
5,
100
]
"""
if i >= self.num_chunks or i < 0:
raise IndexError('Chunk index out of range.')
return pyarrow_wrap_array(self.chunked_array.chunk(i))
@property
def chunks(self):
"""
Convert to a list of single-chunked arrays.
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, None], [4, 5, 100]])
>>> n_legs
<pyarrow.lib.ChunkedArray object at ...>
[
[
2,
2,
null
],
[
4,
5,
100
]
]
>>> n_legs.chunks
[<pyarrow.lib.Int64Array object at ...>
[
2,
2,
null
], <pyarrow.lib.Int64Array object at ...>
[
4,
5,
100
]]
"""
return list(self.iterchunks())
def iterchunks(self):
"""
Convert to an iterator of ChunkArrays.
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, None, 100]])
>>> for i in n_legs.iterchunks():
... print(i.null_count)
...
0
1
"""
for i in range(self.num_chunks):
yield self.chunk(i)
def to_pylist(self, *, maps_as_pydicts=None):
"""
Convert to a list of native Python objects.
Parameters
----------
maps_as_pydicts : str, optional, default `None`
Valid values are `None`, 'lossy', or 'strict'.
The default behavior (`None`), is to convert Arrow Map arrays to
Python association lists (list-of-tuples) in the same order as the
Arrow Map, as in [(key1, value1), (key2, value2), ...].
If 'lossy' or 'strict', convert Arrow Map arrays to native Python dicts.
If 'lossy', whenever duplicate keys are detected, a warning will be printed.
The last seen value of a duplicate key will be in the Python dictionary.
If 'strict', this instead results in an exception being raised when detected.
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, None, 100]])
>>> n_legs.to_pylist()
[2, 2, 4, 4, None, 100]
"""
self._assert_cpu()
result = []
for i in range(self.num_chunks):
result += self.chunk(i).to_pylist(maps_as_pydicts=maps_as_pydicts)
return result
def __arrow_c_stream__(self, requested_schema=None):
"""
Export to a C ArrowArrayStream PyCapsule.
Parameters
----------
requested_schema : PyCapsule, default None
The schema to which the stream should be casted, passed as a
PyCapsule containing a C ArrowSchema representation of the
requested schema.
Returns
-------
PyCapsule
A capsule containing a C ArrowArrayStream struct.
"""
self._assert_cpu()
cdef:
ChunkedArray chunked
ArrowArrayStream* c_stream = NULL
if requested_schema is not None:
target_type = DataType._import_from_c_capsule(requested_schema)
if target_type != self.type:
try:
chunked = self.cast(target_type, safe=True)
except ArrowInvalid as e:
raise ValueError(
f"Could not cast {self.type} to requested type {target_type}: {e}"
)
else:
chunked = self
else:
chunked = self
stream_capsule = alloc_c_stream(&c_stream)
with nogil:
check_status(ExportChunkedArray(chunked.sp_chunked_array, c_stream))
return stream_capsule
@staticmethod
def _import_from_c_capsule(stream):
"""
Import ChunkedArray from a C ArrowArrayStream PyCapsule.
Parameters
----------
stream: PyCapsule
A capsule containing a C ArrowArrayStream PyCapsule.
Returns
-------
ChunkedArray
"""
cdef:
ArrowArrayStream* c_stream
shared_ptr[CChunkedArray] c_chunked_array
ChunkedArray self
c_stream = <ArrowArrayStream*>PyCapsule_GetPointer(
stream, 'arrow_array_stream'
)
with nogil:
c_chunked_array = GetResultValue(ImportChunkedArray(c_stream))
self = ChunkedArray.__new__(ChunkedArray)
self.init(c_chunked_array)
return self
@property
def is_cpu(self):
"""
Whether all chunks in the ChunkedArray are CPU-accessible.
"""
if not self._init_is_cpu:
self._is_cpu = self.chunked_array.is_cpu()
self._init_is_cpu = True
return self._is_cpu
def _assert_cpu(self):
if not self.is_cpu:
raise NotImplementedError("Implemented only for data on CPU device")
def chunked_array(arrays, type=None):
"""
Construct chunked array from list of array-like objects
Parameters
----------
arrays : Array, list of Array, or array-like
Must all be the same data type. Can be empty only if type also passed.
Any Arrow-compatible array that implements the Arrow PyCapsule Protocol
(has an ``__arrow_c_array__`` or ``__arrow_c_stream__`` method) can be
passed as well.
type : DataType or string coercible to DataType
Returns
-------
ChunkedArray
Examples
--------
>>> import pyarrow as pa
>>> pa.chunked_array([], type=pa.int8())
<pyarrow.lib.ChunkedArray object at ...>
[
...
]
>>> pa.chunked_array([[2, 2, 4], [4, 5, 100]])
<pyarrow.lib.ChunkedArray object at ...>
[
[
2,
2,
4
],
[
4,
5,
100
]
]
"""
cdef:
Array arr
vector[shared_ptr[CArray]] c_arrays
shared_ptr[CChunkedArray] c_result
shared_ptr[CDataType] c_type
type = ensure_type(type, allow_none=True)
if isinstance(arrays, Array):
arrays = [arrays]
elif hasattr(arrays, "__arrow_c_stream__"):
if type is not None:
requested_type = type.__arrow_c_schema__()
else:
requested_type = None
capsule = arrays.__arrow_c_stream__(requested_type)
result = ChunkedArray._import_from_c_capsule(capsule)
if type is not None and result.type != type:
# __arrow_c_stream__ coerces schema with best effort, so we might
# need to cast it if the producer wasn't able to cast to exact schema.
result = result.cast(type)
return result
elif hasattr(arrays, "__arrow_c_array__"):
arr = array(arrays, type=type)
arrays = [arr]
for x in arrays:
arr = x if isinstance(x, Array) else array(x, type=type)
if type is None:
# it allows more flexible chunked array construction from to coerce
# subsequent arrays to the firstly inferred array type
# it also spares the inference overhead after the first chunk
type = arr.type
c_arrays.push_back(arr.sp_array)
c_type = pyarrow_unwrap_data_type(type)
with nogil:
c_result = GetResultValue(CChunkedArray.Make(c_arrays, c_type))
return pyarrow_wrap_chunked_array(c_result)
cdef _schema_from_arrays(arrays, names, metadata, shared_ptr[CSchema]* schema):
cdef:
Py_ssize_t K = len(arrays)
c_string c_name
shared_ptr[CDataType] c_type
shared_ptr[const CKeyValueMetadata] c_meta
vector[shared_ptr[CField]] c_fields
if metadata is not None:
c_meta = KeyValueMetadata(metadata).unwrap()
if K == 0:
if names is None or len(names) == 0:
schema.reset(new CSchema(c_fields, c_meta))
return arrays
else:
raise ValueError('Length of names ({}) does not match '
'length of arrays ({})'.format(len(names), K))
c_fields.resize(K)
if names is None:
raise ValueError('Must pass names or schema when constructing '
'Table or RecordBatch.')
if len(names) != K:
raise ValueError('Length of names ({}) does not match '
'length of arrays ({})'.format(len(names), K))
converted_arrays = []
for i in range(K):
val = arrays[i]
if not isinstance(val, (Array, ChunkedArray)):
val = array(val)
c_type = (<DataType> val.type).sp_type
if names[i] is None:
c_name = b'None'
else:
c_name = tobytes(names[i])
c_fields[i].reset(new CField(c_name, c_type, True))
converted_arrays.append(val)
schema.reset(new CSchema(c_fields, c_meta))
return converted_arrays
cdef _sanitize_arrays(arrays, names, schema, metadata,
shared_ptr[CSchema]* c_schema):
cdef Schema cy_schema
if schema is None:
converted_arrays = _schema_from_arrays(arrays, names, metadata,
c_schema)
else:
if names is not None:
raise ValueError('Cannot pass both schema and names')
if metadata is not None:
raise ValueError('Cannot pass both schema and metadata')
cy_schema = schema
if len(schema) != len(arrays):
raise ValueError('Schema and number of arrays unequal')
c_schema[0] = cy_schema.sp_schema
converted_arrays = []
for i, item in enumerate(arrays):
item = asarray(item, type=schema[i].type)
converted_arrays.append(item)
return converted_arrays
cdef class _Tabular(_PandasConvertible):
"""Internal: An interface for common operations on tabular objects."""
def __init__(self):
raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly, use "
f"one of the `{self.__class__.__name__}.from_*` functions instead.")
def __array__(self, dtype=None, copy=None):
self._assert_cpu()
if copy is False:
raise ValueError(
"Unable to avoid a copy while creating a numpy array as requested "
f"(converting a pyarrow.{self.__class__.__name__} always results "
"in a copy).\n"
"If using `np.array(obj, copy=False)` replace it with "
"`np.asarray(obj)` to allow a copy when needed"
)
# 'copy' can further be ignored because stacking will result in a copy
column_arrays = [
np.asarray(self.column(i), dtype=dtype) for i in range(self.num_columns)
]
if column_arrays:
arr = np.stack(column_arrays, axis=1)
else:
arr = np.empty((self.num_rows, 0), dtype=dtype)
return arr
def __dataframe__(self, nan_as_null: bool = False, allow_copy: bool = True):
"""
Return the dataframe interchange object implementing the interchange protocol.
Parameters
----------
nan_as_null : bool, default False
Whether to tell the DataFrame to overwrite null values in the data
with ``NaN`` (or ``NaT``).
allow_copy : bool, default True
Whether to allow memory copying when exporting. If set to False
it would cause non-zero-copy exports to fail.
Returns
-------
DataFrame interchange object
The object which consuming library can use to ingress the dataframe.
Notes
-----
Details on the interchange protocol:
https://data-apis.org/dataframe-protocol/latest/index.html
`nan_as_null` currently has no effect; once support for nullable extension
dtypes is added, this value should be propagated to columns.
"""
from pyarrow.interchange.dataframe import _PyArrowDataFrame
return _PyArrowDataFrame(self, nan_as_null, allow_copy)
def __eq__(self, other):
try:
return self.equals(other)
except TypeError:
return NotImplemented
def __getitem__(self, key):
"""
Slice or return column at given index or column name
Parameters
----------
key : integer, str, or slice
Slices with step not equal to 1 (or None) will produce a copy
rather than a zero-copy view
Returns
-------
Array (from RecordBatch) or ChunkedArray (from Table) for column input.
RecordBatch or Table for slice input.
"""
if isinstance(key, slice):
return _normalize_slice(self, key)
return self.column(key)
def __len__(self):
return self.num_rows
def __repr__(self):
if not self._is_initialized():
raise ValueError("This object's internal pointer is NULL, do not "
"use any methods or attributes on this object")
return self.to_string(preview_cols=10)
def _column(self, int i):
raise NotImplementedError
def _ensure_integer_index(self, i):
"""
Ensure integer index (convert string column name to integer if needed).
"""
if isinstance(i, (bytes, str)):
field_indices = self.schema.get_all_field_indices(i)
if len(field_indices) == 0:
raise KeyError("Field \"{}\" does not exist in schema"
.format(i))
elif len(field_indices) > 1:
raise KeyError("Field \"{}\" exists {} times in schema"
.format(i, len(field_indices)))
else:
return field_indices[0]
elif isinstance(i, int):
return i
else:
raise TypeError("Index must either be string or integer")
def _is_initialized(self):
raise NotImplementedError
def column(self, i):
"""
Select single column from Table or RecordBatch.
Parameters
----------
i : int or string
The index or name of the column to retrieve.
Returns
-------
column : Array (for RecordBatch) or ChunkedArray (for Table)
Examples
--------
Table (works similarly for RecordBatch)
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> table = pa.Table.from_pandas(df)
Select a column by numeric index:
>>> table.column(0)
<pyarrow.lib.ChunkedArray object at ...>
[
[
2,
4,
5,
100
]
]
Select a column by its name:
>>> table.column("animals")
<pyarrow.lib.ChunkedArray object at ...>
[
[
"Flamingo",
"Horse",
"Brittle stars",
"Centipede"
]
]
"""
return self._column(self._ensure_integer_index(i))
@property
def column_names(self):
"""
Names of the Table or RecordBatch columns.
Returns
-------
list of str
Examples
--------
Table (works similarly for RecordBatch)
>>> import pyarrow as pa
>>> table = pa.Table.from_arrays([[2, 4, 5, 100],
... ["Flamingo", "Horse", "Brittle stars", "Centipede"]],
... names=['n_legs', 'animals'])
>>> table.column_names
['n_legs', 'animals']
"""
return [self.field(i).name for i in range(self.num_columns)]
@property
def columns(self):
"""
List of all columns in numerical order.
Returns
-------
columns : list of Array (for RecordBatch) or list of ChunkedArray (for Table)
Examples
--------
Table (works similarly for RecordBatch)
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [None, 4, 5, None],
... 'animals': ["Flamingo", "Horse", None, "Centipede"]})
>>> table = pa.Table.from_pandas(df)
>>> table.columns
[<pyarrow.lib.ChunkedArray object at ...>
[
[
null,
4,
5,
null
]
], <pyarrow.lib.ChunkedArray object at ...>
[
[
"Flamingo",
"Horse",
null,
"Centipede"
]
]]
"""
return [self._column(i) for i in range(self.num_columns)]
def drop_null(self):
"""
Remove rows that contain missing values from a Table or RecordBatch.
See :func:`pyarrow.compute.drop_null` for full usage.
Returns
-------
Table or RecordBatch
A tabular object with the same schema, with rows containing
no missing values.
Examples
--------
Table (works similarly for RecordBatch)
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'year': [None, 2022, 2019, 2021],
... 'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", None, "Centipede"]})
>>> table = pa.Table.from_pandas(df)
>>> table.drop_null()
pyarrow.Table
year: double
n_legs: int64
animals: string
----
year: [[2022,2021]]
n_legs: [[4,100]]
animals: [["Horse","Centipede"]]
"""
self._assert_cpu()
return _pc().drop_null(self)
def field(self, i):
"""
Select a schema field by its column name or numeric index.
Parameters
----------
i : int or string
The index or name of the field to retrieve.
Returns
-------
Field
Examples
--------
Table (works similarly for RecordBatch)
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> table = pa.Table.from_pandas(df)
>>> table.field(0)
pyarrow.Field<n_legs: int64>
>>> table.field(1)
pyarrow.Field<animals: string>
"""
return self.schema.field(i)
@classmethod
def from_pydict(cls, mapping, schema=None, metadata=None):
"""
Construct a Table or RecordBatch from Arrow arrays or columns.
Parameters
----------
mapping : dict or Mapping
A mapping of strings to Arrays or Python lists.
schema : Schema, default None
If not passed, will be inferred from the Mapping values.
metadata : dict or Mapping, default None
Optional metadata for the schema (if inferred).
Returns
-------
Table or RecordBatch
Examples
--------
Table (works similarly for RecordBatch)
>>> import pyarrow as pa
>>> n_legs = pa.array([2, 4, 5, 100])
>>> animals = pa.array(["Flamingo", "Horse", "Brittle stars", "Centipede"])
>>> pydict = {'n_legs': n_legs, 'animals': animals}
Construct a Table from a dictionary of arrays:
>>> pa.Table.from_pydict(pydict)
pyarrow.Table
n_legs: int64
animals: string
----
n_legs: [[2,4,5,100]]
animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
>>> pa.Table.from_pydict(pydict).schema
n_legs: int64
animals: string
Construct a Table from a dictionary of arrays with metadata:
>>> my_metadata={"n_legs": "Number of legs per animal"}
>>> pa.Table.from_pydict(pydict, metadata=my_metadata).schema
n_legs: int64
animals: string
-- schema metadata --
n_legs: 'Number of legs per animal'
Construct a Table from a dictionary of arrays with pyarrow schema:
>>> my_schema = pa.schema([
... pa.field('n_legs', pa.int64()),
... pa.field('animals', pa.string())],
... metadata={"n_legs": "Number of legs per animal"})
>>> pa.Table.from_pydict(pydict, schema=my_schema).schema
n_legs: int64
animals: string
-- schema metadata --
n_legs: 'Number of legs per animal'
"""
return _from_pydict(cls=cls,
mapping=mapping,
schema=schema,
metadata=metadata)
@classmethod
def from_pylist(cls, mapping, schema=None, metadata=None):
"""
Construct a Table or RecordBatch from list of rows / dictionaries.
Parameters
----------
mapping : list of dicts of rows
A mapping of strings to row values.
schema : Schema, default None
If not passed, will be inferred from the first row of the
mapping values.
metadata : dict or Mapping, default None
Optional metadata for the schema (if inferred).
Returns
-------
Table or RecordBatch
Examples
--------
Table (works similarly for RecordBatch)
>>> import pyarrow as pa
>>> pylist = [{'n_legs': 2, 'animals': 'Flamingo'},
... {'n_legs': 4, 'animals': 'Dog'}]
Construct a Table from a list of rows:
>>> pa.Table.from_pylist(pylist)
pyarrow.Table
n_legs: int64
animals: string
----
n_legs: [[2,4]]
animals: [["Flamingo","Dog"]]
Construct a Table from a list of rows with metadata:
>>> my_metadata={"n_legs": "Number of legs per animal"}
>>> pa.Table.from_pylist(pylist, metadata=my_metadata).schema
n_legs: int64
animals: string
-- schema metadata --
n_legs: 'Number of legs per animal'
Construct a Table from a list of rows with pyarrow schema:
>>> my_schema = pa.schema([
... pa.field('n_legs', pa.int64()),
... pa.field('animals', pa.string())],
... metadata={"n_legs": "Number of legs per animal"})
>>> pa.Table.from_pylist(pylist, schema=my_schema).schema
n_legs: int64
animals: string
-- schema metadata --
n_legs: 'Number of legs per animal'
"""
return _from_pylist(cls=cls,
mapping=mapping,
schema=schema,
metadata=metadata)
def itercolumns(self):
"""
Iterator over all columns in their numerical order.
Yields
------
Array (for RecordBatch) or ChunkedArray (for Table)
Examples
--------
Table (works similarly for RecordBatch)
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [None, 4, 5, None],
... 'animals': ["Flamingo", "Horse", None, "Centipede"]})
>>> table = pa.Table.from_pandas(df)
>>> for i in table.itercolumns():
... print(i.null_count)
...
2
1
"""
for i in range(self.num_columns):
yield self._column(i)
@property
def num_columns(self):
raise NotImplementedError
@property
def num_rows(self):
raise NotImplementedError
@property
def shape(self):
"""
Dimensions of the table or record batch: (#rows, #columns).
Returns
-------
(int, int)
Number of rows and number of columns.
Examples
--------
>>> import pyarrow as pa
>>> table = pa.table({'n_legs': [None, 4, 5, None],
... 'animals': ["Flamingo", "Horse", None, "Centipede"]})
>>> table.shape
(4, 2)
"""
return (self.num_rows, self.num_columns)
@property
def schema(self):
raise NotImplementedError
def sort_by(self, sorting, **kwargs):
"""
Sort the Table or RecordBatch by one or multiple columns.
Parameters
----------
sorting : str or list[tuple(name, order)]
Name of the column to use to sort (ascending), or
a list of multiple sorting conditions where
each entry is a tuple with column name
and sorting order ("ascending" or "descending")
**kwargs : dict, optional
Additional sorting options.
As allowed by :class:`SortOptions`
Returns
-------
Table or RecordBatch
A new tabular object sorted according to the sort keys.
Examples
--------
Table (works similarly for RecordBatch)
>>> import pandas as pd
>>> import pyarrow as pa
>>> df = pd.DataFrame({'year': [2020, 2022, 2021, 2022, 2019, 2021],
... 'n_legs': [2, 2, 4, 4, 5, 100],
... 'animal': ["Flamingo", "Parrot", "Dog", "Horse",
... "Brittle stars", "Centipede"]})
>>> table = pa.Table.from_pandas(df)
>>> table.sort_by('animal')
pyarrow.Table
year: int64
n_legs: int64
animal: string
----
year: [[2019,2021,2021,2020,2022,2022]]
n_legs: [[5,100,4,2,4,2]]
animal: [["Brittle stars","Centipede","Dog","Flamingo","Horse","Parrot"]]
"""
self._assert_cpu()
if isinstance(sorting, str):
sorting = [(sorting, "ascending")]
indices = _pc().sort_indices(
self,
options=_pc().SortOptions(sort_keys=sorting, **kwargs)
)
return self.take(indices)
def take(self, object indices):
"""
Select rows from a Table or RecordBatch.
See :func:`pyarrow.compute.take` for full usage.
Parameters
----------
indices : Array or array-like
The indices in the tabular object whose rows will be returned.
Returns
-------
Table or RecordBatch
A tabular object with the same schema, containing the taken rows.
Examples
--------
Table (works similarly for RecordBatch)
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'year': [2020, 2022, 2019, 2021],
... 'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> table = pa.Table.from_pandas(df)
>>> table.take([1,3])
pyarrow.Table
year: int64
n_legs: int64
animals: string
----
year: [[2022,2021]]
n_legs: [[4,100]]
animals: [["Horse","Centipede"]]
"""
self._assert_cpu()
return _pc().take(self, indices)
def filter(self, mask, object null_selection_behavior="drop"):
"""
Select rows from the table or record batch based on a boolean mask.
The Table can be filtered based on a mask, which will be passed to
:func:`pyarrow.compute.filter` to perform the filtering, or it can
be filtered through a boolean :class:`.Expression`
Parameters
----------
mask : Array or array-like or .Expression
The boolean mask or the :class:`.Expression` to filter the table with.
null_selection_behavior : str, default "drop"
How nulls in the mask should be handled, does nothing if
an :class:`.Expression` is used.
Returns
-------
filtered : Table or RecordBatch
A tabular object of the same schema, with only the rows selected
by applied filtering
Examples
--------
Using a Table (works similarly for RecordBatch):
>>> import pyarrow as pa
>>> table = pa.table({'year': [2020, 2022, 2019, 2021],
... 'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
Define an expression and select rows:
>>> import pyarrow.compute as pc
>>> expr = pc.field("year") <= 2020
>>> table.filter(expr)
pyarrow.Table
year: int64
n_legs: int64
animals: string
----
year: [[2020,2019]]
n_legs: [[2,5]]
animals: [["Flamingo","Brittle stars"]]
Define a mask and select rows:
>>> mask=[True, True, False, None]
>>> table.filter(mask)
pyarrow.Table
year: int64
n_legs: int64
animals: string
----
year: [[2020,2022]]
n_legs: [[2,4]]
animals: [["Flamingo","Horse"]]
>>> table.filter(mask, null_selection_behavior='emit_null')
pyarrow.Table
year: int64
n_legs: int64
animals: string
----
year: [[2020,2022,null]]
n_legs: [[2,4,null]]
animals: [["Flamingo","Horse",null]]
"""
self._assert_cpu()
if isinstance(mask, _pc().Expression):
return _pac()._filter_table(self, mask)
else:
return _pc().filter(self, mask, null_selection_behavior)
def to_pydict(self, *, maps_as_pydicts=None):
"""
Convert the Table or RecordBatch to a dict or OrderedDict.
Parameters
----------
maps_as_pydicts : str, optional, default `None`
Valid values are `None`, 'lossy', or 'strict'.
The default behavior (`None`), is to convert Arrow Map arrays to
Python association lists (list-of-tuples) in the same order as the
Arrow Map, as in [(key1, value1), (key2, value2), ...].
If 'lossy' or 'strict', convert Arrow Map arrays to native Python dicts.
If 'lossy', whenever duplicate keys are detected, a warning will be printed.
The last seen value of a duplicate key will be in the Python dictionary.
If 'strict', this instead results in an exception being raised when detected.
Returns
-------
dict
Examples
--------
Table (works similarly for RecordBatch)
>>> import pyarrow as pa
>>> n_legs = pa.array([2, 2, 4, 4, 5, 100])
>>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"])
>>> table = pa.Table.from_arrays([n_legs, animals], names=["n_legs", "animals"])
>>> table.to_pydict()
{'n_legs': [2, 2, 4, 4, 5, 100], 'animals': ['Flamingo', 'Parrot', ..., 'Centipede']}
"""
entries = []
for i in range(self.num_columns):
name = self.field(i).name
column = self[i].to_pylist(maps_as_pydicts=maps_as_pydicts)
entries.append((name, column))
return ordered_dict(entries)
def to_pylist(self, *, maps_as_pydicts=None):
"""
Convert the Table or RecordBatch to a list of rows / dictionaries.
Parameters
----------
maps_as_pydicts : str, optional, default `None`
Valid values are `None`, 'lossy', or 'strict'.
The default behavior (`None`), is to convert Arrow Map arrays to
Python association lists (list-of-tuples) in the same order as the
Arrow Map, as in [(key1, value1), (key2, value2), ...].
If 'lossy' or 'strict', convert Arrow Map arrays to native Python dicts.
If 'lossy', whenever duplicate keys are detected, a warning will be printed.
The last seen value of a duplicate key will be in the Python dictionary.
If 'strict', this instead results in an exception being raised when detected.
Returns
-------
list
Examples
--------
Table (works similarly for RecordBatch)
>>> import pyarrow as pa
>>> data = [[2, 4, 5, 100],
... ["Flamingo", "Horse", "Brittle stars", "Centipede"]]
>>> table = pa.table(data, names=["n_legs", "animals"])
>>> table.to_pylist()
[{'n_legs': 2, 'animals': 'Flamingo'}, {'n_legs': 4, 'animals': 'Horse'}, ...
"""
pydict = self.to_pydict(maps_as_pydicts=maps_as_pydicts)
names = self.schema.names
pylist = [{column: pydict[column][row] for column in names}
for row in range(self.num_rows)]
return pylist
def to_string(self, *, show_metadata=False, preview_cols=0):
"""
Return human-readable string representation of Table or RecordBatch.
Parameters
----------
show_metadata : bool, default False
Display Field-level and Schema-level KeyValueMetadata.
preview_cols : int, default 0
Display values of the columns for the first N columns.
Returns
-------
str
"""
# Use less verbose schema output.
schema_as_string = self.schema.to_string(
show_field_metadata=show_metadata,
show_schema_metadata=show_metadata
)
title = 'pyarrow.{}\n{}'.format(type(self).__name__, schema_as_string)
pieces = [title]
if preview_cols:
pieces.append('----')
for i in range(min(self.num_columns, preview_cols)):
pieces.append('{}: {}'.format(
self.field(i).name,
self.column(i).to_string(indent=0, skip_new_lines=True)
))
if preview_cols < self.num_columns:
pieces.append('...')
return '\n'.join(pieces)
def remove_column(self, int i):
# implemented in RecordBatch/Table subclasses
raise NotImplementedError
def drop_columns(self, columns):
"""
Drop one or more columns and return a new Table or RecordBatch.
Parameters
----------
columns : str or list[str]
Field name(s) referencing existing column(s).
Raises
------
KeyError
If any of the passed column names do not exist.
Returns
-------
Table or RecordBatch
A tabular object without the column(s).
Examples
--------
Table (works similarly for RecordBatch)
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> table = pa.Table.from_pandas(df)
Drop one column:
>>> table.drop_columns("animals")
pyarrow.Table
n_legs: int64
----
n_legs: [[2,4,5,100]]
Drop one or more columns:
>>> table.drop_columns(["n_legs", "animals"])
pyarrow.Table
...
----
"""
if isinstance(columns, str):
columns = [columns]
indices = []
for col in columns:
idx = self.schema.get_field_index(col)
if idx == -1:
raise KeyError("Column {!r} not found".format(col))
indices.append(idx)
indices.sort()
indices.reverse()
res = self
for idx in indices:
res = res.remove_column(idx)
return res
def add_column(self, int i, field_, column):
# implemented in RecordBatch/Table subclasses
raise NotImplementedError
def append_column(self, field_, column):
"""
Append column at end of columns.
Parameters
----------
field_ : str or Field
If a string is passed then the type is deduced from the column
data.
column : Array or value coercible to array
Column data.
Returns
-------
Table or RecordBatch
New table or record batch with the passed column added.
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> table = pa.Table.from_pandas(df)
Append column at the end:
>>> year = [2021, 2022, 2019, 2021]
>>> table.append_column('year', [year])
pyarrow.Table
n_legs: int64
animals: string
year: int64
----
n_legs: [[2,4,5,100]]
animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
year: [[2021,2022,2019,2021]]
"""
return self.add_column(self.num_columns, field_, column)
cdef void _assert_cpu(self) except *:
return
cdef class RecordBatch(_Tabular):
"""
Batch of rows of columns of equal length
Warnings
--------
Do not call this class's constructor directly, use one of the
``RecordBatch.from_*`` functions instead.
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.array([2, 2, 4, 4, 5, 100])
>>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"])
>>> names = ["n_legs", "animals"]
Constructing a RecordBatch from arrays:
>>> pa.RecordBatch.from_arrays([n_legs, animals], names=names)
pyarrow.RecordBatch
n_legs: int64
animals: string
----
n_legs: [2,2,4,4,5,100]
animals: ["Flamingo","Parrot","Dog","Horse","Brittle stars","Centipede"]
>>> pa.RecordBatch.from_arrays([n_legs, animals], names=names).to_pandas()
n_legs animals
0 2 Flamingo
1 2 Parrot
2 4 Dog
3 4 Horse
4 5 Brittle stars
5 100 Centipede
Constructing a RecordBatch from pandas DataFrame:
>>> import pandas as pd
>>> df = pd.DataFrame({'year': [2020, 2022, 2021, 2022],
... 'month': [3, 5, 7, 9],
... 'day': [1, 5, 9, 13],
... 'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> pa.RecordBatch.from_pandas(df)
pyarrow.RecordBatch
year: int64
month: int64
day: int64
n_legs: int64
animals: string
----
year: [2020,2022,2021,2022]
month: [3,5,7,9]
day: [1,5,9,13]
n_legs: [2,4,5,100]
animals: ["Flamingo","Horse","Brittle stars","Centipede"]
>>> pa.RecordBatch.from_pandas(df).to_pandas()
year month day n_legs animals
0 2020 3 1 2 Flamingo
1 2022 5 5 4 Horse
2 2021 7 9 5 Brittle stars
3 2022 9 13 100 Centipede
Constructing a RecordBatch from pylist:
>>> pylist = [{'n_legs': 2, 'animals': 'Flamingo'},
... {'n_legs': 4, 'animals': 'Dog'}]
>>> pa.RecordBatch.from_pylist(pylist).to_pandas()
n_legs animals
0 2 Flamingo
1 4 Dog
You can also construct a RecordBatch using :func:`pyarrow.record_batch`:
>>> pa.record_batch([n_legs, animals], names=names).to_pandas()
n_legs animals
0 2 Flamingo
1 2 Parrot
2 4 Dog
3 4 Horse
4 5 Brittle stars
5 100 Centipede
>>> pa.record_batch(df)
pyarrow.RecordBatch
year: int64
month: int64
day: int64
n_legs: int64
animals: string
----
year: [2020,2022,2021,2022]
month: [3,5,7,9]
day: [1,5,9,13]
n_legs: [2,4,5,100]
animals: ["Flamingo","Horse","Brittle stars","Centipede"]
"""
def __cinit__(self):
self.batch = NULL
self._schema = None
cdef void init(self, const shared_ptr[CRecordBatch]& batch):
self.sp_batch = batch
self.batch = batch.get()
def _is_initialized(self):
return self.batch != NULL
def __reduce__(self):
self._assert_cpu()
return _reconstruct_record_batch, (self.columns, self.schema)
def validate(self, *, full=False):
"""
Perform validation checks. An exception is raised if validation fails.
By default only cheap validation checks are run. Pass `full=True`
for thorough validation checks (potentially O(n)).
Parameters
----------
full : bool, default False
If True, run expensive checks, otherwise cheap checks only.
Raises
------
ArrowInvalid
"""
if full:
self._assert_cpu()
with nogil:
check_status(self.batch.ValidateFull())
else:
with nogil:
check_status(self.batch.Validate())
def replace_schema_metadata(self, metadata=None):
"""
Create shallow copy of record batch by replacing schema
key-value metadata with the indicated new metadata (which may be None,
which deletes any existing metadata
Parameters
----------
metadata : dict, default None
Returns
-------
shallow_copy : RecordBatch
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.array([2, 2, 4, 4, 5, 100])
Constructing a RecordBatch with schema and metadata:
>>> my_schema = pa.schema([
... pa.field('n_legs', pa.int64())],
... metadata={"n_legs": "Number of legs per animal"})
>>> batch = pa.RecordBatch.from_arrays([n_legs], schema=my_schema)
>>> batch.schema
n_legs: int64
-- schema metadata --
n_legs: 'Number of legs per animal'
Shallow copy of a RecordBatch with deleted schema metadata:
>>> batch.replace_schema_metadata().schema
n_legs: int64
"""
cdef:
shared_ptr[const CKeyValueMetadata] c_meta
shared_ptr[CRecordBatch] c_batch
metadata = ensure_metadata(metadata, allow_none=True)
c_meta = pyarrow_unwrap_metadata(metadata)
with nogil:
c_batch = self.batch.ReplaceSchemaMetadata(c_meta)
return pyarrow_wrap_batch(c_batch)
@property
def num_columns(self):
"""
Number of columns
Returns
-------
int
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.array([2, 2, 4, 4, 5, 100])
>>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"])
>>> batch = pa.RecordBatch.from_arrays([n_legs, animals],
... names=["n_legs", "animals"])
>>> batch.num_columns
2
"""
return self.batch.num_columns()
@property
def num_rows(self):
"""
Number of rows
Due to the definition of a RecordBatch, all columns have the same
number of rows.
Returns
-------
int
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.array([2, 2, 4, 4, 5, 100])
>>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"])
>>> batch = pa.RecordBatch.from_arrays([n_legs, animals],
... names=["n_legs", "animals"])
>>> batch.num_rows
6
"""
return self.batch.num_rows()
@property
def schema(self):
"""
Schema of the RecordBatch and its columns
Returns
-------
pyarrow.Schema
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.array([2, 2, 4, 4, 5, 100])
>>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"])
>>> batch = pa.RecordBatch.from_arrays([n_legs, animals],
... names=["n_legs", "animals"])
>>> batch.schema
n_legs: int64
animals: string
"""
if self._schema is None:
self._schema = pyarrow_wrap_schema(self.batch.schema())
return self._schema
def _column(self, int i):
"""
Select single column from record batch by its numeric index.
Parameters
----------
i : int
The index of the column to retrieve.
Returns
-------
column : pyarrow.Array
"""
cdef int index = <int> _normalize_index(i, self.num_columns)
cdef Array result = pyarrow_wrap_array(self.batch.column(index))
result._name = self.schema[index].name
return result
@property
def nbytes(self):
"""
Total number of bytes consumed by the elements of the record batch.
In other words, the sum of bytes from all buffer ranges referenced.
Unlike `get_total_buffer_size` this method will account for array
offsets.
If buffers are shared between arrays then the shared
portion will only be counted multiple times.
The dictionary of dictionary arrays will always be counted in their
entirety even if the array only references a portion of the dictionary.
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.array([2, 2, 4, 4, 5, 100])
>>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"])
>>> batch = pa.RecordBatch.from_arrays([n_legs, animals],
... names=["n_legs", "animals"])
>>> batch.nbytes
116
"""
self._assert_cpu()
cdef:
CResult[int64_t] c_res_buffer
with nogil:
c_res_buffer = ReferencedBufferSize(deref(self.batch))
size = GetResultValue(c_res_buffer)
return size
def get_total_buffer_size(self):
"""
The sum of bytes in each buffer referenced by the record batch
An array may only reference a portion of a buffer.
This method will overestimate in this case and return the
byte size of the entire buffer.
If a buffer is referenced multiple times then it will
only be counted once.
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.array([2, 2, 4, 4, 5, 100])
>>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"])
>>> batch = pa.RecordBatch.from_arrays([n_legs, animals],
... names=["n_legs", "animals"])
>>> batch.get_total_buffer_size()
120
"""
self._assert_cpu()
cdef:
int64_t total_buffer_size
total_buffer_size = TotalBufferSize(deref(self.batch))
return total_buffer_size
def __sizeof__(self):
return super(RecordBatch, self).__sizeof__() + self.nbytes
def add_column(self, int i, field_, column):
"""
Add column to RecordBatch at position i.
A new record batch is returned with the column added, the original record batch
object is left unchanged.
Parameters
----------
i : int
Index to place the column at.
field_ : str or Field
If a string is passed then the type is deduced from the column
data.
column : Array or value coercible to array
Column data.
Returns
-------
RecordBatch
New record batch with the passed column added.
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> batch = pa.RecordBatch.from_pandas(df)
Add column:
>>> year = [2021, 2022, 2019, 2021]
>>> batch.add_column(0,"year", year)
pyarrow.RecordBatch
year: int64
n_legs: int64
animals: string
----
year: [2021,2022,2019,2021]
n_legs: [2,4,5,100]
animals: ["Flamingo","Horse","Brittle stars","Centipede"]
Original record batch is left unchanged:
>>> batch
pyarrow.RecordBatch
n_legs: int64
animals: string
----
n_legs: [2,4,5,100]
animals: ["Flamingo","Horse","Brittle stars","Centipede"]
"""
cdef:
shared_ptr[CRecordBatch] c_batch
Field c_field
Array c_arr
CDeviceAllocationType device_type = self.sp_batch.get().device_type()
if isinstance(column, Array):
c_arr = column
else:
c_arr = array(column)
if device_type != c_arr.sp_array.get().device_type():
raise TypeError("The column must be allocated on the same "
"device as the RecordBatch. Got column on "
f"device {c_arr.device_type!r}, but expected "
f"{self.device_type!r}.")
if isinstance(field_, Field):
c_field = field_
else:
c_field = field(field_, c_arr.type)
with nogil:
c_batch = GetResultValue(self.batch.AddColumn(
i, c_field.sp_field, c_arr.sp_array))
return pyarrow_wrap_batch(c_batch)
def remove_column(self, int i):
"""
Create new RecordBatch with the indicated column removed.
Parameters
----------
i : int
Index of column to remove.
Returns
-------
Table
New record batch without the column.
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> batch = pa.RecordBatch.from_pandas(df)
>>> batch.remove_column(1)
pyarrow.RecordBatch
n_legs: int64
----
n_legs: [2,4,5,100]
"""
cdef shared_ptr[CRecordBatch] c_batch
with nogil:
c_batch = GetResultValue(self.batch.RemoveColumn(i))
return pyarrow_wrap_batch(c_batch)
def set_column(self, int i, field_, column):
"""
Replace column in RecordBatch at position.
Parameters
----------
i : int
Index to place the column at.
field_ : str or Field
If a string is passed then the type is deduced from the column
data.
column : Array or value coercible to array
Column data.
Returns
-------
RecordBatch
New record batch with the passed column set.
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> batch = pa.RecordBatch.from_pandas(df)
Replace a column:
>>> year = [2021, 2022, 2019, 2021]
>>> batch.set_column(1,'year', year)
pyarrow.RecordBatch
n_legs: int64
year: int64
----
n_legs: [2,4,5,100]
year: [2021,2022,2019,2021]
"""
cdef:
shared_ptr[CRecordBatch] c_batch
Field c_field
Array c_arr
CDeviceAllocationType device_type = self.sp_batch.get().device_type()
if isinstance(column, Array):
c_arr = column
else:
c_arr = array(column)
if device_type != c_arr.sp_array.get().device_type():
raise TypeError("The column must be allocated on the same "
"device as the RecordBatch. Got column on "
f"device {c_arr.device_type!r}, but expected "
f"{self.device_type!r}.")
if isinstance(field_, Field):
c_field = field_
else:
c_field = field(field_, c_arr.type)
with nogil:
c_batch = GetResultValue(self.batch.SetColumn(
i, c_field.sp_field, c_arr.sp_array))
return pyarrow_wrap_batch(c_batch)
def rename_columns(self, names):
"""
Create new record batch with columns renamed to provided names.
Parameters
----------
names : list[str] or dict[str, str]
List of new column names or mapping of old column names to new column names.
If a mapping of old to new column names is passed, then all columns which are
found to match a provided old column name will be renamed to the new column name.
If any column names are not found in the mapping, a KeyError will be raised.
Raises
------
KeyError
If any of the column names passed in the names mapping do not exist.
Returns
-------
RecordBatch
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> batch = pa.RecordBatch.from_pandas(df)
>>> new_names = ["n", "name"]
>>> batch.rename_columns(new_names)
pyarrow.RecordBatch
n: int64
name: string
----
n: [2,4,5,100]
name: ["Flamingo","Horse","Brittle stars","Centipede"]
>>> new_names = {"n_legs": "n", "animals": "name"}
>>> batch.rename_columns(new_names)
pyarrow.RecordBatch
n: int64
name: string
----
n: [2,4,5,100]
name: ["Flamingo","Horse","Brittle stars","Centipede"]
"""
cdef:
shared_ptr[CRecordBatch] c_batch
vector[c_string] c_names
if isinstance(names, (list, tuple)):
for name in names:
c_names.push_back(tobytes(name))
elif isinstance(names, dict):
idx_to_new_name = {}
for name, new_name in names.items():
indices = self.schema.get_all_field_indices(name)
if not indices:
raise KeyError("Column {!r} not found".format(name))
for index in indices:
idx_to_new_name[index] = new_name
for i in range(self.num_columns):
new_name = idx_to_new_name.get(i, self.column_names[i])
c_names.push_back(tobytes(new_name))
else:
raise TypeError(f"names must be a list or dict not {type(names)!r}")
with nogil:
c_batch = GetResultValue(self.batch.RenameColumns(move(c_names)))
return pyarrow_wrap_batch(c_batch)
def serialize(self, memory_pool=None):
"""
Write RecordBatch to Buffer as encapsulated IPC message, which does not
include a Schema.
To reconstruct a RecordBatch from the encapsulated IPC message Buffer
returned by this function, a Schema must be passed separately. See
Examples.
Parameters
----------
memory_pool : MemoryPool, default None
Uses default memory pool if not specified
Returns
-------
serialized : Buffer
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.array([2, 2, 4, 4, 5, 100])
>>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"])
>>> batch = pa.RecordBatch.from_arrays([n_legs, animals],
... names=["n_legs", "animals"])
>>> buf = batch.serialize()
>>> buf
<pyarrow.Buffer address=0x... size=... is_cpu=True is_mutable=True>
Reconstruct RecordBatch from IPC message Buffer and original Schema
>>> pa.ipc.read_record_batch(buf, batch.schema)
pyarrow.RecordBatch
n_legs: int64
animals: string
----
n_legs: [2,2,4,4,5,100]
animals: ["Flamingo","Parrot","Dog","Horse","Brittle stars","Centipede"]
"""
self._assert_cpu()
cdef shared_ptr[CBuffer] buffer
cdef CIpcWriteOptions options = CIpcWriteOptions.Defaults()
options.memory_pool = maybe_unbox_memory_pool(memory_pool)
with nogil:
buffer = GetResultValue(
SerializeRecordBatch(deref(self.batch), options))
return pyarrow_wrap_buffer(buffer)
def slice(self, offset=0, length=None):
"""
Compute zero-copy slice of this RecordBatch
Parameters
----------
offset : int, default 0
Offset from start of record batch to slice
length : int, default None
Length of slice (default is until end of batch starting from
offset)
Returns
-------
sliced : RecordBatch
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.array([2, 2, 4, 4, 5, 100])
>>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"])
>>> batch = pa.RecordBatch.from_arrays([n_legs, animals],
... names=["n_legs", "animals"])
>>> batch.to_pandas()
n_legs animals
0 2 Flamingo
1 2 Parrot
2 4 Dog
3 4 Horse
4 5 Brittle stars
5 100 Centipede
>>> batch.slice(offset=3).to_pandas()
n_legs animals
0 4 Horse
1 5 Brittle stars
2 100 Centipede
>>> batch.slice(length=2).to_pandas()
n_legs animals
0 2 Flamingo
1 2 Parrot
>>> batch.slice(offset=3, length=1).to_pandas()
n_legs animals
0 4 Horse
"""
cdef shared_ptr[CRecordBatch] result
if offset < 0:
raise IndexError('Offset must be non-negative')
offset = min(len(self), offset)
if length is None:
result = self.batch.Slice(offset)
else:
result = self.batch.Slice(offset, length)
return pyarrow_wrap_batch(result)
def equals(self, object other, bint check_metadata=False):
"""
Check if contents of two record batches are equal.
Parameters
----------
other : pyarrow.RecordBatch
RecordBatch to compare against.
check_metadata : bool, default False
Whether schema metadata equality should be checked as well.
Returns
-------
are_equal : bool
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.array([2, 2, 4, 4, 5, 100])
>>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"])
>>> batch = pa.RecordBatch.from_arrays([n_legs, animals],
... names=["n_legs", "animals"])
>>> batch_0 = pa.record_batch([])
>>> batch_1 = pa.RecordBatch.from_arrays([n_legs, animals],
... names=["n_legs", "animals"],
... metadata={"n_legs": "Number of legs per animal"})
>>> batch.equals(batch)
True
>>> batch.equals(batch_0)
False
>>> batch.equals(batch_1)
True
>>> batch.equals(batch_1, check_metadata=True)
False
"""
self._assert_cpu()
cdef:
CRecordBatch* this_batch = self.batch
shared_ptr[CRecordBatch] other_batch = pyarrow_unwrap_batch(other)
c_bool result
if not other_batch:
return False
with nogil:
result = this_batch.Equals(deref(other_batch), check_metadata)
return result
def select(self, object columns):
"""
Select columns of the RecordBatch.
Returns a new RecordBatch with the specified columns, and metadata
preserved.
Parameters
----------
columns : list-like
The column names or integer indices to select.
Returns
-------
RecordBatch
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.array([2, 2, 4, 4, 5, 100])
>>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"])
>>> batch = pa.record_batch([n_legs, animals],
... names=["n_legs", "animals"])
Select columns my indices:
>>> batch.select([1])
pyarrow.RecordBatch
animals: string
----
animals: ["Flamingo","Parrot","Dog","Horse","Brittle stars","Centipede"]
Select columns by names:
>>> batch.select(["n_legs"])
pyarrow.RecordBatch
n_legs: int64
----
n_legs: [2,2,4,4,5,100]
"""
cdef:
shared_ptr[CRecordBatch] c_batch
vector[int] c_indices
for idx in columns:
idx = self._ensure_integer_index(idx)
idx = _normalize_index(idx, self.num_columns)
c_indices.push_back(<int> idx)
with nogil:
c_batch = GetResultValue(self.batch.SelectColumns(move(c_indices)))
return pyarrow_wrap_batch(c_batch)
def cast(self, Schema target_schema, safe=None, options=None):
"""
Cast record batch values to another schema.
Parameters
----------
target_schema : Schema
Schema to cast to, the names and order of fields must match.
safe : bool, default True
Check for overflows or other unsafe conversions.
options : CastOptions, default None
Additional checks pass by CastOptions
Returns
-------
RecordBatch
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> batch = pa.RecordBatch.from_pandas(df)
>>> batch.schema
n_legs: int64
animals: string
-- schema metadata --
pandas: '{"index_columns": [{"kind": "range", "name": null, "start": 0, ...
Define new schema and cast batch values:
>>> my_schema = pa.schema([
... pa.field('n_legs', pa.duration('s')),
... pa.field('animals', pa.string())]
... )
>>> batch.cast(target_schema=my_schema)
pyarrow.RecordBatch
n_legs: duration[s]
animals: string
----
n_legs: [2,4,5,100]
animals: ["Flamingo","Horse","Brittle stars","Centipede"]
"""
cdef:
Array column, casted
Field field
list newcols = []
if self.schema.names != target_schema.names:
raise ValueError("Target schema's field names are not matching "
"the record batch's field names: {!r}, {!r}"
.format(self.schema.names, target_schema.names))
for column, field in zip(self.itercolumns(), target_schema):
if not field.nullable and column.null_count > 0:
raise ValueError("Casting field {!r} with null values to non-nullable"
.format(field.name))
casted = column.cast(field.type, safe=safe, options=options)
newcols.append(casted)
return RecordBatch.from_arrays(newcols, schema=target_schema)
def _to_pandas(self, options, **kwargs):
self._assert_cpu()
return Table.from_batches([self])._to_pandas(options, **kwargs)
@classmethod
def from_pandas(cls, df, Schema schema=None, preserve_index=None,
nthreads=None, columns=None):
"""
Convert pandas.DataFrame to an Arrow RecordBatch
Parameters
----------
df : pandas.DataFrame
schema : pyarrow.Schema, optional
The expected schema of the RecordBatch. This can be used to
indicate the type of columns if we cannot infer it automatically.
If passed, the output will have exactly this schema. Columns
specified in the schema that are not found in the DataFrame columns
or its index will raise an error. Additional columns or index
levels in the DataFrame which are not specified in the schema will
be ignored.
preserve_index : bool, optional
Whether to store the index as an additional column in the resulting
``RecordBatch``. The default of None will store the index as a
column, except for RangeIndex which is stored as metadata only. Use
``preserve_index=True`` to force it to be stored as a column.
nthreads : int, default None
If greater than 1, convert columns to Arrow in parallel using
indicated number of threads. By default, this follows
:func:`pyarrow.cpu_count` (may use up to system CPU count threads).
columns : list, optional
List of column to be converted. If None, use all columns.
Returns
-------
pyarrow.RecordBatch
Examples
--------
>>> import pandas as pd
>>> df = pd.DataFrame({'year': [2020, 2022, 2021, 2022],
... 'month': [3, 5, 7, 9],
... 'day': [1, 5, 9, 13],
... 'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
Convert pandas DataFrame to RecordBatch:
>>> import pyarrow as pa
>>> pa.RecordBatch.from_pandas(df)
pyarrow.RecordBatch
year: int64
month: int64
day: int64
n_legs: int64
animals: string
----
year: [2020,2022,2021,2022]
month: [3,5,7,9]
day: [1,5,9,13]
n_legs: [2,4,5,100]
animals: ["Flamingo","Horse","Brittle stars","Centipede"]
Convert pandas DataFrame to RecordBatch using schema:
>>> my_schema = pa.schema([
... pa.field('n_legs', pa.int64()),
... pa.field('animals', pa.string())],
... metadata={"n_legs": "Number of legs per animal"})
>>> pa.RecordBatch.from_pandas(df, schema=my_schema)
pyarrow.RecordBatch
n_legs: int64
animals: string
----
n_legs: [2,4,5,100]
animals: ["Flamingo","Horse","Brittle stars","Centipede"]
Convert pandas DataFrame to RecordBatch specifying columns:
>>> pa.RecordBatch.from_pandas(df, columns=["n_legs"])
pyarrow.RecordBatch
n_legs: int64
----
n_legs: [2,4,5,100]
"""
from pyarrow.pandas_compat import dataframe_to_arrays
arrays, schema, n_rows = dataframe_to_arrays(
df, schema, preserve_index, nthreads=nthreads, columns=columns
)
# If df is empty but row index is not, create empty RecordBatch with rows >0
cdef vector[shared_ptr[CArray]] c_arrays
if n_rows:
return pyarrow_wrap_batch(CRecordBatch.Make((<Schema> schema).sp_schema,
n_rows, c_arrays))
else:
return cls.from_arrays(arrays, schema=schema)
@staticmethod
def from_arrays(list arrays, names=None, schema=None, metadata=None):
"""
Construct a RecordBatch from multiple pyarrow.Arrays
Parameters
----------
arrays : list of pyarrow.Array
One for each field in RecordBatch
names : list of str, optional
Names for the batch fields. If not passed, schema must be passed
schema : Schema, default None
Schema for the created batch. If not passed, names must be passed
metadata : dict or Mapping, default None
Optional metadata for the schema (if inferred).
Returns
-------
pyarrow.RecordBatch
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.array([2, 2, 4, 4, 5, 100])
>>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"])
>>> names = ["n_legs", "animals"]
Construct a RecordBatch from pyarrow Arrays using names:
>>> pa.RecordBatch.from_arrays([n_legs, animals], names=names)
pyarrow.RecordBatch
n_legs: int64
animals: string
----
n_legs: [2,2,4,4,5,100]
animals: ["Flamingo","Parrot","Dog","Horse","Brittle stars","Centipede"]
>>> pa.RecordBatch.from_arrays([n_legs, animals], names=names).to_pandas()
n_legs animals
0 2 Flamingo
1 2 Parrot
2 4 Dog
3 4 Horse
4 5 Brittle stars
5 100 Centipede
Construct a RecordBatch from pyarrow Arrays using schema:
>>> my_schema = pa.schema([
... pa.field('n_legs', pa.int64()),
... pa.field('animals', pa.string())],
... metadata={"n_legs": "Number of legs per animal"})
>>> pa.RecordBatch.from_arrays([n_legs, animals], schema=my_schema).to_pandas()
n_legs animals
0 2 Flamingo
1 2 Parrot
2 4 Dog
3 4 Horse
4 5 Brittle stars
5 100 Centipede
>>> pa.RecordBatch.from_arrays([n_legs, animals], schema=my_schema).schema
n_legs: int64
animals: string
-- schema metadata --
n_legs: 'Number of legs per animal'
"""
cdef:
Array arr
shared_ptr[CSchema] c_schema
vector[shared_ptr[CArray]] c_arrays
int64_t num_rows
if len(arrays) > 0:
num_rows = len(arrays[0])
else:
num_rows = 0
if isinstance(names, Schema):
import warnings
warnings.warn("Schema passed to names= option, please "
"pass schema= explicitly. "
"Will raise exception in future", FutureWarning)
schema = names
names = None
converted_arrays = _sanitize_arrays(arrays, names, schema, metadata,
&c_schema)
c_arrays.reserve(len(arrays))
for arr in converted_arrays:
if len(arr) != num_rows:
raise ValueError('Arrays were not all the same length: '
'{0} vs {1}'.format(len(arr), num_rows))
c_arrays.push_back(arr.sp_array)
result = pyarrow_wrap_batch(CRecordBatch.Make(c_schema, num_rows,
c_arrays))
result.validate()
return result
@staticmethod
def from_struct_array(StructArray struct_array):
"""
Construct a RecordBatch from a StructArray.
Each field in the StructArray will become a column in the resulting
``RecordBatch``.
Parameters
----------
struct_array : StructArray
Array to construct the record batch from.
Returns
-------
pyarrow.RecordBatch
Examples
--------
>>> import pyarrow as pa
>>> struct = pa.array([{'n_legs': 2, 'animals': 'Parrot'},
... {'year': 2022, 'n_legs': 4}])
>>> pa.RecordBatch.from_struct_array(struct).to_pandas()
animals n_legs year
0 Parrot 2 NaN
1 None 4 2022.0
"""
cdef:
shared_ptr[CRecordBatch] c_record_batch
if struct_array.sp_array.get().device_type() != CDeviceAllocationType_kCPU:
raise NotImplementedError("Implemented only for data on CPU device")
with nogil:
c_record_batch = GetResultValue(
CRecordBatch.FromStructArray(struct_array.sp_array))
return pyarrow_wrap_batch(c_record_batch)
def to_struct_array(self):
"""
Convert to a struct array.
"""
self._assert_cpu()
cdef:
shared_ptr[CRecordBatch] c_record_batch
shared_ptr[CArray] c_array
c_record_batch = pyarrow_unwrap_batch(self)
with nogil:
c_array = GetResultValue(
<CResult[shared_ptr[CArray]]>deref(c_record_batch).ToStructArray())
return pyarrow_wrap_array(c_array)
def to_tensor(self, c_bool null_to_nan=False, c_bool row_major=True, MemoryPool memory_pool=None):
"""
Convert to a :class:`~pyarrow.Tensor`.
RecordBatches that can be converted have fields of type signed or unsigned
integer or float, including all bit-widths.
``null_to_nan`` is ``False`` by default and this method will raise an error in case
any nulls are present. RecordBatches with nulls can be converted with ``null_to_nan``
set to ``True``. In this case null values are converted to ``NaN`` and integer type
arrays are promoted to the appropriate float type.
Parameters
----------
null_to_nan : bool, default False
Whether to write null values in the result as ``NaN``.
row_major : bool, default True
Whether resulting Tensor is row-major or column-major
memory_pool : MemoryPool, default None
For memory allocations, if required, otherwise use default pool
Examples
--------
>>> import pyarrow as pa
>>> batch = pa.record_batch(
... [
... pa.array([1, 2, 3, 4, None], type=pa.int32()),
... pa.array([10, 20, 30, 40, None], type=pa.float32()),
... ], names = ["a", "b"]
... )
>>> batch
pyarrow.RecordBatch
a: int32
b: float
----
a: [1,2,3,4,null]
b: [10,20,30,40,null]
Convert a RecordBatch to row-major Tensor with null values
written as ``NaN``s
>>> batch.to_tensor(null_to_nan=True)
<pyarrow.Tensor>
type: double
shape: (5, 2)
strides: (16, 8)
>>> batch.to_tensor(null_to_nan=True).to_numpy()
array([[ 1., 10.],
[ 2., 20.],
[ 3., 30.],
[ 4., 40.],
[nan, nan]])
Convert a RecordBatch to column-major Tensor
>>> batch.to_tensor(null_to_nan=True, row_major=False)
<pyarrow.Tensor>
type: double
shape: (5, 2)
strides: (8, 40)
>>> batch.to_tensor(null_to_nan=True, row_major=False).to_numpy()
array([[ 1., 10.],
[ 2., 20.],
[ 3., 30.],
[ 4., 40.],
[nan, nan]])
"""
self._assert_cpu()
cdef:
shared_ptr[CRecordBatch] c_record_batch
shared_ptr[CTensor] c_tensor
CMemoryPool* pool = maybe_unbox_memory_pool(memory_pool)
c_record_batch = pyarrow_unwrap_batch(self)
with nogil:
c_tensor = GetResultValue(
<CResult[shared_ptr[CTensor]]>deref(c_record_batch).ToTensor(null_to_nan,
row_major, pool))
return pyarrow_wrap_tensor(c_tensor)
def copy_to(self, destination):
"""
Copy the entire RecordBatch to destination device.
This copies each column of the record batch to create
a new record batch where all underlying buffers for the columns have
been copied to the destination MemoryManager.
Parameters
----------
destination : pyarrow.MemoryManager or pyarrow.Device
The destination device to copy the array to.
Returns
-------
RecordBatch
"""
cdef:
shared_ptr[CRecordBatch] c_batch
shared_ptr[CMemoryManager] c_memory_manager
if isinstance(destination, Device):
c_memory_manager = (<Device>destination).unwrap().get().default_memory_manager()
elif isinstance(destination, MemoryManager):
c_memory_manager = (<MemoryManager>destination).unwrap()
else:
raise TypeError(
"Argument 'destination' has incorrect type (expected a "
f"pyarrow Device or MemoryManager, got {type(destination)})"
)
with nogil:
c_batch = GetResultValue(self.batch.CopyTo(c_memory_manager))
return pyarrow_wrap_batch(c_batch)
def _export_to_c(self, out_ptr, out_schema_ptr=0):
"""
Export to a C ArrowArray struct, given its pointer.
If a C ArrowSchema struct pointer is also given, the record batch
schema is exported to it at the same time.
Parameters
----------
out_ptr: int
The raw pointer to a C ArrowArray struct.
out_schema_ptr: int (optional)
The raw pointer to a C ArrowSchema struct.
Be careful: if you don't pass the ArrowArray struct to a consumer,
array memory will leak. This is a low-level function intended for
expert users.
"""
cdef:
void* c_ptr = _as_c_pointer(out_ptr)
void* c_schema_ptr = _as_c_pointer(out_schema_ptr,
allow_null=True)
with nogil:
check_status(ExportRecordBatch(deref(self.sp_batch),
<ArrowArray*> c_ptr,
<ArrowSchema*> c_schema_ptr))
@staticmethod
def _import_from_c(in_ptr, schema):
"""
Import RecordBatch from a C ArrowArray struct, given its pointer
and the imported schema.
Parameters
----------
in_ptr: int
The raw pointer to a C ArrowArray struct.
type: Schema or int
Either a Schema object, or the raw pointer to a C ArrowSchema
struct.
This is a low-level function intended for expert users.
"""
cdef:
void* c_ptr = _as_c_pointer(in_ptr)
void* c_schema_ptr
shared_ptr[CRecordBatch] c_batch
c_schema = pyarrow_unwrap_schema(schema)
if c_schema == nullptr:
# Not a Schema object, perhaps a raw ArrowSchema pointer
c_schema_ptr = _as_c_pointer(schema, allow_null=True)
with nogil:
c_batch = GetResultValue(ImportRecordBatch(
<ArrowArray*> c_ptr, <ArrowSchema*> c_schema_ptr))
else:
with nogil:
c_batch = GetResultValue(ImportRecordBatch(
<ArrowArray*> c_ptr, c_schema))
return pyarrow_wrap_batch(c_batch)
def __arrow_c_array__(self, requested_schema=None):
"""
Get a pair of PyCapsules containing a C ArrowArray representation of the object.
Parameters
----------
requested_schema : PyCapsule | None
A PyCapsule containing a C ArrowSchema representation of a requested
schema. PyArrow will attempt to cast the batch to this schema.
If None, the batch will be returned as-is, with a schema matching the
one returned by :meth:`__arrow_c_schema__()`.
Returns
-------
Tuple[PyCapsule, PyCapsule]
A pair of PyCapsules containing a C ArrowSchema and ArrowArray,
respectively.
"""
self._assert_cpu()
cdef:
ArrowArray* c_array
ArrowSchema* c_schema
if requested_schema is not None:
target_schema = Schema._import_from_c_capsule(requested_schema)
if target_schema != self.schema:
try:
casted_batch = self.cast(target_schema, safe=True)
inner_batch = pyarrow_unwrap_batch(casted_batch)
except ArrowInvalid as e:
raise ValueError(
f"Could not cast {self.schema} to requested schema {target_schema}: {e}"
)
else:
inner_batch = self.sp_batch
else:
inner_batch = self.sp_batch
schema_capsule = alloc_c_schema(&c_schema)
array_capsule = alloc_c_array(&c_array)
with nogil:
check_status(ExportRecordBatch(deref(inner_batch), c_array, c_schema))
return schema_capsule, array_capsule
def __arrow_c_stream__(self, requested_schema=None):
"""
Export the batch as an Arrow C stream PyCapsule.
Parameters
----------
requested_schema : PyCapsule, default None
The schema to which the stream should be casted, passed as a
PyCapsule containing a C ArrowSchema representation of the
requested schema.
Currently, this is not supported and will raise a
NotImplementedError if the schema doesn't match the current schema.
Returns
-------
PyCapsule
"""
self._assert_cpu()
return Table.from_batches([self]).__arrow_c_stream__(requested_schema)
@staticmethod
def _import_from_c_capsule(schema_capsule, array_capsule):
"""
Import RecordBatch from a pair of PyCapsules containing a C ArrowSchema
and ArrowArray, respectively.
Parameters
----------
schema_capsule : PyCapsule
A PyCapsule containing a C ArrowSchema representation of the schema.
array_capsule : PyCapsule
A PyCapsule containing a C ArrowArray representation of the array.
Returns
-------
pyarrow.RecordBatch
"""
cdef:
ArrowSchema* c_schema
ArrowArray* c_array
shared_ptr[CRecordBatch] c_batch
c_schema = <ArrowSchema*> PyCapsule_GetPointer(schema_capsule, 'arrow_schema')
c_array = <ArrowArray*> PyCapsule_GetPointer(array_capsule, 'arrow_array')
with nogil:
c_batch = GetResultValue(ImportRecordBatch(c_array, c_schema))
return pyarrow_wrap_batch(c_batch)
def _export_to_c_device(self, out_ptr, out_schema_ptr=0):
"""
Export to a C ArrowDeviceArray struct, given its pointer.
If a C ArrowSchema struct pointer is also given, the record batch
schema is exported to it at the same time.
Parameters
----------
out_ptr: int
The raw pointer to a C ArrowDeviceArray struct.
out_schema_ptr: int (optional)
The raw pointer to a C ArrowSchema struct.
Be careful: if you don't pass the ArrowDeviceArray struct to a consumer,
array memory will leak. This is a low-level function intended for
expert users.
"""
cdef:
void* c_ptr = _as_c_pointer(out_ptr)
void* c_schema_ptr = _as_c_pointer(out_schema_ptr,
allow_null=True)
with nogil:
check_status(ExportDeviceRecordBatch(
deref(self.sp_batch), <shared_ptr[CSyncEvent]>NULL,
<ArrowDeviceArray*> c_ptr, <ArrowSchema*> c_schema_ptr)
)
@staticmethod
def _import_from_c_device(in_ptr, schema):
"""
Import RecordBatch from a C ArrowDeviceArray struct, given its pointer
and the imported schema.
Parameters
----------
in_ptr: int
The raw pointer to a C ArrowDeviceArray struct.
type: Schema or int
Either a Schema object, or the raw pointer to a C ArrowSchema
struct.
This is a low-level function intended for expert users.
"""
cdef:
ArrowDeviceArray* c_device_array = <ArrowDeviceArray*>_as_c_pointer(in_ptr)
void* c_schema_ptr
shared_ptr[CRecordBatch] c_batch
if c_device_array.device_type == ARROW_DEVICE_CUDA:
_ensure_cuda_loaded()
c_schema = pyarrow_unwrap_schema(schema)
if c_schema == nullptr:
# Not a Schema object, perhaps a raw ArrowSchema pointer
c_schema_ptr = _as_c_pointer(schema, allow_null=True)
with nogil:
c_batch = GetResultValue(ImportDeviceRecordBatch(
c_device_array, <ArrowSchema*> c_schema_ptr))
else:
with nogil:
c_batch = GetResultValue(ImportDeviceRecordBatch(
c_device_array, c_schema))
return pyarrow_wrap_batch(c_batch)
def __arrow_c_device_array__(self, requested_schema=None, **kwargs):
"""
Get a pair of PyCapsules containing a C ArrowDeviceArray representation
of the object.
Parameters
----------
requested_schema : PyCapsule | None
A PyCapsule containing a C ArrowSchema representation of a requested
schema. PyArrow will attempt to cast the batch to this data type.
If None, the batch will be returned as-is, with a type matching the
one returned by :meth:`__arrow_c_schema__()`.
kwargs
Currently no additional keyword arguments are supported, but
this method will accept any keyword with a value of ``None``
for compatibility with future keywords.
Returns
-------
Tuple[PyCapsule, PyCapsule]
A pair of PyCapsules containing a C ArrowSchema and ArrowDeviceArray,
respectively.
"""
cdef:
ArrowDeviceArray* c_array
ArrowSchema* c_schema
shared_ptr[CRecordBatch] inner_batch
non_default_kwargs = [
name for name, value in kwargs.items() if value is not None
]
if non_default_kwargs:
raise NotImplementedError(
f"Received unsupported keyword argument(s): {non_default_kwargs}"
)
if requested_schema is not None:
target_schema = Schema._import_from_c_capsule(requested_schema)
if target_schema != self.schema:
if not self.is_cpu:
raise NotImplementedError(
"Casting to a requested schema is only supported for CPU data"
)
try:
casted_batch = self.cast(target_schema, safe=True)
inner_batch = pyarrow_unwrap_batch(casted_batch)
except ArrowInvalid as e:
raise ValueError(
f"Could not cast {self.schema} to requested schema {target_schema}: {e}"
)
else:
inner_batch = self.sp_batch
else:
inner_batch = self.sp_batch
schema_capsule = alloc_c_schema(&c_schema)
array_capsule = alloc_c_device_array(&c_array)
with nogil:
check_status(ExportDeviceRecordBatch(
deref(inner_batch), <shared_ptr[CSyncEvent]>NULL, c_array, c_schema))
return schema_capsule, array_capsule
@staticmethod
def _import_from_c_device_capsule(schema_capsule, array_capsule):
"""
Import RecordBatch from a pair of PyCapsules containing a
C ArrowSchema and ArrowDeviceArray, respectively.
Parameters
----------
schema_capsule : PyCapsule
A PyCapsule containing a C ArrowSchema representation of the schema.
array_capsule : PyCapsule
A PyCapsule containing a C ArrowDeviceArray representation of the array.
Returns
-------
pyarrow.RecordBatch
"""
cdef:
ArrowSchema* c_schema
ArrowDeviceArray* c_array
shared_ptr[CRecordBatch] batch
c_schema = <ArrowSchema*> PyCapsule_GetPointer(schema_capsule, 'arrow_schema')
c_array = <ArrowDeviceArray*> PyCapsule_GetPointer(
array_capsule, 'arrow_device_array'
)
with nogil:
batch = GetResultValue(ImportDeviceRecordBatch(c_array, c_schema))
return pyarrow_wrap_batch(batch)
@property
def device_type(self):
"""
The device type where the arrays in the RecordBatch reside.
Returns
-------
DeviceAllocationType
"""
return _wrap_device_allocation_type(self.sp_batch.get().device_type())
@property
def is_cpu(self):
"""
Whether the RecordBatch's arrays are CPU-accessible.
"""
return self.device_type == DeviceAllocationType.CPU
cdef void _assert_cpu(self) except *:
if self.sp_batch.get().device_type() != CDeviceAllocationType_kCPU:
raise NotImplementedError("Implemented only for data on CPU device")
def _reconstruct_record_batch(columns, schema):
"""
Internal: reconstruct RecordBatch from pickled components.
"""
return RecordBatch.from_arrays(columns, schema=schema)
def table_to_blocks(options, Table table, categories, extension_columns):
cdef:
PyObject* result_obj
shared_ptr[CTable] c_table
CMemoryPool* pool
PandasOptions c_options = _convert_pandas_options(options)
if categories is not None:
c_options.categorical_columns = {tobytes(cat) for cat in categories}
if extension_columns is not None:
c_options.extension_columns = {tobytes(col)
for col in extension_columns}
if pandas_api.is_v1():
# ARROW-3789: Coerce date/timestamp types to datetime64[ns]
c_options.coerce_temporal_nanoseconds = True
if c_options.self_destruct:
# Move the shared_ptr, table is now unsafe to use further
c_table = move(table.sp_table)
table.table = NULL
else:
c_table = table.sp_table
with nogil:
check_status(
libarrow_python.ConvertTableToPandas(c_options, move(c_table),
&result_obj)
)
return PyObject_to_object(result_obj)
cdef class Table(_Tabular):
"""
A collection of top-level named, equal length Arrow arrays.
Warnings
--------
Do not call this class's constructor directly, use one of the ``from_*``
methods instead.
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.array([2, 4, 5, 100])
>>> animals = pa.array(["Flamingo", "Horse", "Brittle stars", "Centipede"])
>>> names = ["n_legs", "animals"]
Construct a Table from arrays:
>>> pa.Table.from_arrays([n_legs, animals], names=names)
pyarrow.Table
n_legs: int64
animals: string
----
n_legs: [[2,4,5,100]]
animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
Construct a Table from a RecordBatch:
>>> batch = pa.record_batch([n_legs, animals], names=names)
>>> pa.Table.from_batches([batch])
pyarrow.Table
n_legs: int64
animals: string
----
n_legs: [[2,4,5,100]]
animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
Construct a Table from pandas DataFrame:
>>> import pandas as pd
>>> df = pd.DataFrame({'year': [2020, 2022, 2019, 2021],
... 'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> pa.Table.from_pandas(df)
pyarrow.Table
year: int64
n_legs: int64
animals: string
----
year: [[2020,2022,2019,2021]]
n_legs: [[2,4,5,100]]
animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
Construct a Table from a dictionary of arrays:
>>> pydict = {'n_legs': n_legs, 'animals': animals}
>>> pa.Table.from_pydict(pydict)
pyarrow.Table
n_legs: int64
animals: string
----
n_legs: [[2,4,5,100]]
animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
>>> pa.Table.from_pydict(pydict).schema
n_legs: int64
animals: string
Construct a Table from a dictionary of arrays with metadata:
>>> my_metadata={"n_legs": "Number of legs per animal"}
>>> pa.Table.from_pydict(pydict, metadata=my_metadata).schema
n_legs: int64
animals: string
-- schema metadata --
n_legs: 'Number of legs per animal'
Construct a Table from a list of rows:
>>> pylist = [{'n_legs': 2, 'animals': 'Flamingo'}, {'year': 2021, 'animals': 'Centipede'}]
>>> pa.Table.from_pylist(pylist)
pyarrow.Table
n_legs: int64
animals: string
----
n_legs: [[2,null]]
animals: [["Flamingo","Centipede"]]
Construct a Table from a list of rows with pyarrow schema:
>>> my_schema = pa.schema([
... pa.field('year', pa.int64()),
... pa.field('n_legs', pa.int64()),
... pa.field('animals', pa.string())],
... metadata={"year": "Year of entry"})
>>> pa.Table.from_pylist(pylist, schema=my_schema).schema
year: int64
n_legs: int64
animals: string
-- schema metadata --
year: 'Year of entry'
Construct a Table with :func:`pyarrow.table`:
>>> pa.table([n_legs, animals], names=names)
pyarrow.Table
n_legs: int64
animals: string
----
n_legs: [[2,4,5,100]]
animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
"""
def __cinit__(self):
self.table = NULL
self._init_is_cpu = False
cdef void init(self, const shared_ptr[CTable]& table):
self.sp_table = table
self.table = table.get()
def _is_initialized(self):
return self.table != NULL
def validate(self, *, full=False):
"""
Perform validation checks. An exception is raised if validation fails.
By default only cheap validation checks are run. Pass `full=True`
for thorough validation checks (potentially O(n)).
Parameters
----------
full : bool, default False
If True, run expensive checks, otherwise cheap checks only.
Raises
------
ArrowInvalid
"""
if full:
self._assert_cpu()
with nogil:
check_status(self.table.ValidateFull())
else:
with nogil:
check_status(self.table.Validate())
def __reduce__(self):
# Reduce the columns as ChunkedArrays to avoid serializing schema
# data twice
self._assert_cpu()
columns = [col for col in self.columns]
return _reconstruct_table, (columns, self.schema)
def slice(self, offset=0, length=None):
"""
Compute zero-copy slice of this Table.
Parameters
----------
offset : int, default 0
Offset from start of table to slice.
length : int, default None
Length of slice (default is until end of table starting from
offset).
Returns
-------
Table
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'year': [2020, 2022, 2019, 2021],
... 'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> table = pa.Table.from_pandas(df)
>>> table.slice(length=3)
pyarrow.Table
year: int64
n_legs: int64
animals: string
----
year: [[2020,2022,2019]]
n_legs: [[2,4,5]]
animals: [["Flamingo","Horse","Brittle stars"]]
>>> table.slice(offset=2)
pyarrow.Table
year: int64
n_legs: int64
animals: string
----
year: [[2019,2021]]
n_legs: [[5,100]]
animals: [["Brittle stars","Centipede"]]
>>> table.slice(offset=2, length=1)
pyarrow.Table
year: int64
n_legs: int64
animals: string
----
year: [[2019]]
n_legs: [[5]]
animals: [["Brittle stars"]]
"""
cdef shared_ptr[CTable] result
if offset < 0:
raise IndexError('Offset must be non-negative')
offset = min(len(self), offset)
if length is None:
result = self.table.Slice(offset)
else:
result = self.table.Slice(offset, length)
return pyarrow_wrap_table(result)
def select(self, object columns):
"""
Select columns of the Table.
Returns a new Table with the specified columns, and metadata
preserved.
Parameters
----------
columns : list-like
The column names or integer indices to select.
Returns
-------
Table
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'year': [2020, 2022, 2019, 2021],
... 'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> table = pa.Table.from_pandas(df)
>>> table.select([0,1])
pyarrow.Table
year: int64
n_legs: int64
----
year: [[2020,2022,2019,2021]]
n_legs: [[2,4,5,100]]
>>> table.select(["year"])
pyarrow.Table
year: int64
----
year: [[2020,2022,2019,2021]]
"""
cdef:
shared_ptr[CTable] c_table
vector[int] c_indices
for idx in columns:
idx = self._ensure_integer_index(idx)
idx = _normalize_index(idx, self.num_columns)
c_indices.push_back(<int> idx)
with nogil:
c_table = GetResultValue(self.table.SelectColumns(move(c_indices)))
return pyarrow_wrap_table(c_table)
def replace_schema_metadata(self, metadata=None):
"""
Create shallow copy of table by replacing schema
key-value metadata with the indicated new metadata (which may be None),
which deletes any existing metadata.
Parameters
----------
metadata : dict, default None
Returns
-------
Table
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'year': [2020, 2022, 2019, 2021],
... 'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> table = pa.Table.from_pandas(df)
Constructing a Table with pyarrow schema and metadata:
>>> my_schema = pa.schema([
... pa.field('n_legs', pa.int64()),
... pa.field('animals', pa.string())],
... metadata={"n_legs": "Number of legs per animal"})
>>> table= pa.table(df, my_schema)
>>> table.schema
n_legs: int64
animals: string
-- schema metadata --
n_legs: 'Number of legs per animal'
pandas: ...
Create a shallow copy of a Table with deleted schema metadata:
>>> table.replace_schema_metadata().schema
n_legs: int64
animals: string
Create a shallow copy of a Table with new schema metadata:
>>> metadata={"animals": "Which animal"}
>>> table.replace_schema_metadata(metadata = metadata).schema
n_legs: int64
animals: string
-- schema metadata --
animals: 'Which animal'
"""
cdef:
shared_ptr[const CKeyValueMetadata] c_meta
shared_ptr[CTable] c_table
metadata = ensure_metadata(metadata, allow_none=True)
c_meta = pyarrow_unwrap_metadata(metadata)
with nogil:
c_table = self.table.ReplaceSchemaMetadata(c_meta)
return pyarrow_wrap_table(c_table)
def flatten(self, MemoryPool memory_pool=None):
"""
Flatten this Table.
Each column with a struct type is flattened
into one column per struct field. Other columns are left unchanged.
Parameters
----------
memory_pool : MemoryPool, default None
For memory allocations, if required, otherwise use default pool
Returns
-------
Table
Examples
--------
>>> import pyarrow as pa
>>> struct = pa.array([{'n_legs': 2, 'animals': 'Parrot'},
... {'year': 2022, 'n_legs': 4}])
>>> month = pa.array([4, 6])
>>> table = pa.Table.from_arrays([struct,month],
... names = ["a", "month"])
>>> table
pyarrow.Table
a: struct<animals: string, n_legs: int64, year: int64>
child 0, animals: string
child 1, n_legs: int64
child 2, year: int64
month: int64
----
a: [
-- is_valid: all not null
-- child 0 type: string
["Parrot",null]
-- child 1 type: int64
[2,4]
-- child 2 type: int64
[null,2022]]
month: [[4,6]]
Flatten the columns with struct field:
>>> table.flatten()
pyarrow.Table
a.animals: string
a.n_legs: int64
a.year: int64
month: int64
----
a.animals: [["Parrot",null]]
a.n_legs: [[2,4]]
a.year: [[null,2022]]
month: [[4,6]]
"""
self._assert_cpu()
cdef:
shared_ptr[CTable] flattened
CMemoryPool* pool = maybe_unbox_memory_pool(memory_pool)
with nogil:
flattened = GetResultValue(self.table.Flatten(pool))
return pyarrow_wrap_table(flattened)
def combine_chunks(self, MemoryPool memory_pool=None):
"""
Make a new table by combining the chunks this table has.
All the underlying chunks in the ChunkedArray of each column are
concatenated into zero or one chunk.
Parameters
----------
memory_pool : MemoryPool, default None
For memory allocations, if required, otherwise use default pool.
Returns
-------
Table
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, 5, 100]])
>>> animals = pa.chunked_array([["Flamingo", "Parrot", "Dog"], ["Horse", "Brittle stars", "Centipede"]])
>>> names = ["n_legs", "animals"]
>>> table = pa.table([n_legs, animals], names=names)
>>> table
pyarrow.Table
n_legs: int64
animals: string
----
n_legs: [[2,2,4],[4,5,100]]
animals: [["Flamingo","Parrot","Dog"],["Horse","Brittle stars","Centipede"]]
>>> table.combine_chunks()
pyarrow.Table
n_legs: int64
animals: string
----
n_legs: [[2,2,4,4,5,100]]
animals: [["Flamingo","Parrot","Dog","Horse","Brittle stars","Centipede"]]
"""
self._assert_cpu()
cdef:
shared_ptr[CTable] combined
CMemoryPool* pool = maybe_unbox_memory_pool(memory_pool)
with nogil:
combined = GetResultValue(self.table.CombineChunks(pool))
return pyarrow_wrap_table(combined)
def unify_dictionaries(self, MemoryPool memory_pool=None):
"""
Unify dictionaries across all chunks.
This method returns an equivalent table, but where all chunks of
each column share the same dictionary values. Dictionary indices
are transposed accordingly.
Columns without dictionaries are returned unchanged.
Parameters
----------
memory_pool : MemoryPool, default None
For memory allocations, if required, otherwise use default pool
Returns
-------
Table
Examples
--------
>>> import pyarrow as pa
>>> arr_1 = pa.array(["Flamingo", "Parrot", "Dog"]).dictionary_encode()
>>> arr_2 = pa.array(["Horse", "Brittle stars", "Centipede"]).dictionary_encode()
>>> c_arr = pa.chunked_array([arr_1, arr_2])
>>> table = pa.table([c_arr], names=["animals"])
>>> table
pyarrow.Table
animals: dictionary<values=string, indices=int32, ordered=0>
----
animals: [ -- dictionary:
["Flamingo","Parrot","Dog"] -- indices:
[0,1,2], -- dictionary:
["Horse","Brittle stars","Centipede"] -- indices:
[0,1,2]]
Unify dictionaries across both chunks:
>>> table.unify_dictionaries()
pyarrow.Table
animals: dictionary<values=string, indices=int32, ordered=0>
----
animals: [ -- dictionary:
["Flamingo","Parrot","Dog","Horse","Brittle stars","Centipede"] -- indices:
[0,1,2], -- dictionary:
["Flamingo","Parrot","Dog","Horse","Brittle stars","Centipede"] -- indices:
[3,4,5]]
"""
self._assert_cpu()
cdef:
CMemoryPool* pool = maybe_unbox_memory_pool(memory_pool)
shared_ptr[CTable] c_result
with nogil:
c_result = GetResultValue(CDictionaryUnifier.UnifyTable(
deref(self.table), pool))
return pyarrow_wrap_table(c_result)
def equals(self, Table other, bint check_metadata=False):
"""
Check if contents of two tables are equal.
Parameters
----------
other : pyarrow.Table
Table to compare against.
check_metadata : bool, default False
Whether schema metadata equality should be checked as well.
Returns
-------
bool
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.array([2, 2, 4, 4, 5, 100])
>>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"])
>>> names=["n_legs", "animals"]
>>> table = pa.Table.from_arrays([n_legs, animals], names=names)
>>> table_0 = pa.Table.from_arrays([])
>>> table_1 = pa.Table.from_arrays([n_legs, animals],
... names=names,
... metadata={"n_legs": "Number of legs per animal"})
>>> table.equals(table)
True
>>> table.equals(table_0)
False
>>> table.equals(table_1)
True
>>> table.equals(table_1, check_metadata=True)
False
"""
self._assert_cpu()
if other is None:
return False
cdef:
CTable* this_table = self.table
CTable* other_table = other.table
c_bool result
with nogil:
result = this_table.Equals(deref(other_table), check_metadata)
return result
def cast(self, Schema target_schema, safe=None, options=None):
"""
Cast table values to another schema.
Parameters
----------
target_schema : Schema
Schema to cast to, the names and order of fields must match.
safe : bool, default True
Check for overflows or other unsafe conversions.
options : CastOptions, default None
Additional checks pass by CastOptions
Returns
-------
Table
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> table = pa.Table.from_pandas(df)
>>> table.schema
n_legs: int64
animals: string
-- schema metadata --
pandas: '{"index_columns": [{"kind": "range", "name": null, "start": 0, ...
Define new schema and cast table values:
>>> my_schema = pa.schema([
... pa.field('n_legs', pa.duration('s')),
... pa.field('animals', pa.string())]
... )
>>> table.cast(target_schema=my_schema)
pyarrow.Table
n_legs: duration[s]
animals: string
----
n_legs: [[2,4,5,100]]
animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
"""
self._assert_cpu()
cdef:
ChunkedArray column, casted
Field field
list newcols = []
if self.schema.names != target_schema.names:
raise ValueError("Target schema's field names are not matching "
"the table's field names: {!r}, {!r}"
.format(self.schema.names, target_schema.names))
for column, field in zip(self.itercolumns(), target_schema):
if not field.nullable and column.null_count > 0:
raise ValueError("Casting field {!r} with null values to non-nullable"
.format(field.name))
casted = column.cast(field.type, safe=safe, options=options)
newcols.append(casted)
return Table.from_arrays(newcols, schema=target_schema)
@classmethod
def from_pandas(cls, df, Schema schema=None, preserve_index=None,
nthreads=None, columns=None, bint safe=True):
"""
Convert pandas.DataFrame to an Arrow Table.
The column types in the resulting Arrow Table are inferred from the
dtypes of the pandas.Series in the DataFrame. In the case of non-object
Series, the NumPy dtype is translated to its Arrow equivalent. In the
case of `object`, we need to guess the datatype by looking at the
Python objects in this Series.
Be aware that Series of the `object` dtype don't carry enough
information to always lead to a meaningful Arrow type. In the case that
we cannot infer a type, e.g. because the DataFrame is of length 0 or
the Series only contains None/nan objects, the type is set to
null. This behavior can be avoided by constructing an explicit schema
and passing it to this function.
Parameters
----------
df : pandas.DataFrame
schema : pyarrow.Schema, optional
The expected schema of the Arrow Table. This can be used to
indicate the type of columns if we cannot infer it automatically.
If passed, the output will have exactly this schema. Columns
specified in the schema that are not found in the DataFrame columns
or its index will raise an error. Additional columns or index
levels in the DataFrame which are not specified in the schema will
be ignored.
preserve_index : bool, optional
Whether to store the index as an additional column in the resulting
``Table``. The default of None will store the index as a column,
except for RangeIndex which is stored as metadata only. Use
``preserve_index=True`` to force it to be stored as a column.
nthreads : int, default None
If greater than 1, convert columns to Arrow in parallel using
indicated number of threads. By default, this follows
:func:`pyarrow.cpu_count` (may use up to system CPU count threads).
columns : list, optional
List of column to be converted. If None, use all columns.
safe : bool, default True
Check for overflows or other unsafe conversions.
Returns
-------
Table
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> pa.Table.from_pandas(df)
pyarrow.Table
n_legs: int64
animals: string
----
n_legs: [[2,4,5,100]]
animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
"""
from pyarrow.pandas_compat import dataframe_to_arrays
arrays, schema, n_rows = dataframe_to_arrays(
df,
schema=schema,
preserve_index=preserve_index,
nthreads=nthreads,
columns=columns,
safe=safe
)
# If df is empty but row index is not, create empty Table with rows >0
cdef vector[shared_ptr[CChunkedArray]] c_arrays
if n_rows:
return pyarrow_wrap_table(
CTable.MakeWithRows((<Schema> schema).sp_schema, c_arrays, n_rows))
else:
return cls.from_arrays(arrays, schema=schema)
@staticmethod
def from_arrays(arrays, names=None, schema=None, metadata=None):
"""
Construct a Table from Arrow arrays.
Parameters
----------
arrays : list of pyarrow.Array or pyarrow.ChunkedArray
Equal-length arrays that should form the table.
names : list of str, optional
Names for the table columns. If not passed, schema must be passed.
schema : Schema, default None
Schema for the created table. If not passed, names must be passed.
metadata : dict or Mapping, default None
Optional metadata for the schema (if inferred).
Returns
-------
Table
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.array([2, 4, 5, 100])
>>> animals = pa.array(["Flamingo", "Horse", "Brittle stars", "Centipede"])
>>> names = ["n_legs", "animals"]
Construct a Table from arrays:
>>> pa.Table.from_arrays([n_legs, animals], names=names)
pyarrow.Table
n_legs: int64
animals: string
----
n_legs: [[2,4,5,100]]
animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
Construct a Table from arrays with metadata:
>>> my_metadata={"n_legs": "Number of legs per animal"}
>>> pa.Table.from_arrays([n_legs, animals],
... names=names,
... metadata=my_metadata)
pyarrow.Table
n_legs: int64
animals: string
----
n_legs: [[2,4,5,100]]
animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
>>> pa.Table.from_arrays([n_legs, animals],
... names=names,
... metadata=my_metadata).schema
n_legs: int64
animals: string
-- schema metadata --
n_legs: 'Number of legs per animal'
Construct a Table from arrays with pyarrow schema:
>>> my_schema = pa.schema([
... pa.field('n_legs', pa.int64()),
... pa.field('animals', pa.string())],
... metadata={"animals": "Name of the animal species"})
>>> pa.Table.from_arrays([n_legs, animals],
... schema=my_schema)
pyarrow.Table
n_legs: int64
animals: string
----
n_legs: [[2,4,5,100]]
animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
>>> pa.Table.from_arrays([n_legs, animals],
... schema=my_schema).schema
n_legs: int64
animals: string
-- schema metadata --
animals: 'Name of the animal species'
"""
cdef:
vector[shared_ptr[CChunkedArray]] columns
shared_ptr[CSchema] c_schema
int i, K = <int> len(arrays)
converted_arrays = _sanitize_arrays(arrays, names, schema, metadata,
&c_schema)
columns.reserve(K)
for item in converted_arrays:
if isinstance(item, Array):
columns.push_back(
make_shared[CChunkedArray](
(<Array> item).sp_array
)
)
elif isinstance(item, ChunkedArray):
columns.push_back((<ChunkedArray> item).sp_chunked_array)
else:
raise TypeError(type(item))
result = pyarrow_wrap_table(CTable.Make(c_schema, columns))
result.validate()
return result
@staticmethod
def from_struct_array(struct_array):
"""
Construct a Table from a StructArray.
Each field in the StructArray will become a column in the resulting
``Table``.
Parameters
----------
struct_array : StructArray or ChunkedArray
Array to construct the table from.
Returns
-------
pyarrow.Table
Examples
--------
>>> import pyarrow as pa
>>> struct = pa.array([{'n_legs': 2, 'animals': 'Parrot'},
... {'year': 2022, 'n_legs': 4}])
>>> pa.Table.from_struct_array(struct).to_pandas()
animals n_legs year
0 Parrot 2 NaN
1 None 4 2022.0
"""
if isinstance(struct_array, Array):
return Table.from_batches([RecordBatch.from_struct_array(struct_array)])
else:
return Table.from_batches([
RecordBatch.from_struct_array(chunk)
for chunk in struct_array.chunks
])
def to_struct_array(self, max_chunksize=None):
"""
Convert to a chunked array of struct type.
Parameters
----------
max_chunksize : int, default None
Maximum number of rows for ChunkedArray chunks. Individual chunks
may be smaller depending on the chunk layout of individual columns.
Returns
-------
ChunkedArray
"""
self._assert_cpu()
return chunked_array([
batch.to_struct_array()
for batch in self.to_batches(max_chunksize=max_chunksize)
])
@staticmethod
def from_batches(batches, Schema schema=None):
"""
Construct a Table from a sequence or iterator of Arrow RecordBatches.
Parameters
----------
batches : sequence or iterator of RecordBatch
Sequence of RecordBatch to be converted, all schemas must be equal.
schema : Schema, default None
If not passed, will be inferred from the first RecordBatch.
Returns
-------
Table
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.array([2, 4, 5, 100])
>>> animals = pa.array(["Flamingo", "Horse", "Brittle stars", "Centipede"])
>>> names = ["n_legs", "animals"]
>>> batch = pa.record_batch([n_legs, animals], names=names)
>>> batch.to_pandas()
n_legs animals
0 2 Flamingo
1 4 Horse
2 5 Brittle stars
3 100 Centipede
Construct a Table from a RecordBatch:
>>> pa.Table.from_batches([batch])
pyarrow.Table
n_legs: int64
animals: string
----
n_legs: [[2,4,5,100]]
animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
Construct a Table from a sequence of RecordBatches:
>>> pa.Table.from_batches([batch, batch])
pyarrow.Table
n_legs: int64
animals: string
----
n_legs: [[2,4,5,100],[2,4,5,100]]
animals: [["Flamingo","Horse","Brittle stars","Centipede"],["Flamingo","Horse","Brittle stars","Centipede"]]
"""
cdef:
vector[shared_ptr[CRecordBatch]] c_batches
shared_ptr[CTable] c_table
shared_ptr[CSchema] c_schema
RecordBatch batch
for batch in batches:
c_batches.push_back(batch.sp_batch)
if schema is None:
if c_batches.size() == 0:
raise ValueError('Must pass schema, or at least '
'one RecordBatch')
c_schema = c_batches[0].get().schema()
else:
c_schema = schema.sp_schema
with nogil:
c_table = GetResultValue(
CTable.FromRecordBatches(c_schema, move(c_batches)))
return pyarrow_wrap_table(c_table)
def to_batches(self, max_chunksize=None):
"""
Convert Table to a list of RecordBatch objects.
Note that this method is zero-copy, it merely exposes the same data
under a different API.
Parameters
----------
max_chunksize : int, default None
Maximum number of rows for each RecordBatch chunk. Individual chunks
may be smaller depending on the chunk layout of individual columns.
Returns
-------
list[RecordBatch]
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> table = pa.Table.from_pandas(df)
Convert a Table to a RecordBatch:
>>> table.to_batches()[0].to_pandas()
n_legs animals
0 2 Flamingo
1 4 Horse
2 5 Brittle stars
3 100 Centipede
Convert a Table to a list of RecordBatches:
>>> table.to_batches(max_chunksize=2)[0].to_pandas()
n_legs animals
0 2 Flamingo
1 4 Horse
>>> table.to_batches(max_chunksize=2)[1].to_pandas()
n_legs animals
0 5 Brittle stars
1 100 Centipede
"""
cdef:
unique_ptr[TableBatchReader] reader
int64_t c_max_chunksize
list result = []
shared_ptr[CRecordBatch] batch
reader.reset(new TableBatchReader(deref(self.table)))
if max_chunksize is not None:
if not max_chunksize > 0:
raise ValueError("'max_chunksize' should be strictly positive")
c_max_chunksize = max_chunksize
reader.get().set_chunksize(c_max_chunksize)
while True:
with nogil:
check_status(reader.get().ReadNext(&batch))
if batch.get() == NULL:
break
result.append(pyarrow_wrap_batch(batch))
return result
def to_reader(self, max_chunksize=None):
"""
Convert the Table to a RecordBatchReader.
Note that this method is zero-copy, it merely exposes the same data
under a different API.
Parameters
----------
max_chunksize : int, default None
Maximum number of rows for each RecordBatch chunk. Individual chunks
may be smaller depending on the chunk layout of individual columns.
Returns
-------
RecordBatchReader
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> table = pa.Table.from_pandas(df)
Convert a Table to a RecordBatchReader:
>>> table.to_reader()
<pyarrow.lib.RecordBatchReader object at ...>
>>> reader = table.to_reader()
>>> reader.schema
n_legs: int64
animals: string
-- schema metadata --
pandas: '{"index_columns": [{"kind": "range", "name": null, "start": 0, ...
>>> reader.read_all()
pyarrow.Table
n_legs: int64
animals: string
----
n_legs: [[2,4,5,100]]
animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
"""
cdef:
shared_ptr[CRecordBatchReader] c_reader
RecordBatchReader reader
shared_ptr[TableBatchReader] t_reader
t_reader = make_shared[TableBatchReader](self.sp_table)
if max_chunksize is not None:
t_reader.get().set_chunksize(max_chunksize)
c_reader = dynamic_pointer_cast[CRecordBatchReader, TableBatchReader](
t_reader)
reader = RecordBatchReader.__new__(RecordBatchReader)
reader.reader = c_reader
return reader
def _to_pandas(self, options, categories=None, ignore_metadata=False,
types_mapper=None):
self._assert_cpu()
from pyarrow.pandas_compat import table_to_dataframe
df = table_to_dataframe(
options, self, categories,
ignore_metadata=ignore_metadata,
types_mapper=types_mapper)
return df
@property
def schema(self):
"""
Schema of the table and its columns.
Returns
-------
Schema
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> table = pa.Table.from_pandas(df)
>>> table.schema
n_legs: int64
animals: string
-- schema metadata --
pandas: '{"index_columns": [{"kind": "range", "name": null, "start": 0, "' ...
"""
return pyarrow_wrap_schema(self.table.schema())
def _column(self, int i):
"""
Select a column by its numeric index.
Parameters
----------
i : int
The index of the column to retrieve.
Returns
-------
ChunkedArray
"""
cdef int index = <int> _normalize_index(i, self.num_columns)
cdef ChunkedArray result = pyarrow_wrap_chunked_array(
self.table.column(index))
result._name = self.schema[index].name
return result
@property
def num_columns(self):
"""
Number of columns in this table.
Returns
-------
int
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [None, 4, 5, None],
... 'animals': ["Flamingo", "Horse", None, "Centipede"]})
>>> table = pa.Table.from_pandas(df)
>>> table.num_columns
2
"""
return self.table.num_columns()
@property
def num_rows(self):
"""
Number of rows in this table.
Due to the definition of a table, all columns have the same number of
rows.
Returns
-------
int
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [None, 4, 5, None],
... 'animals': ["Flamingo", "Horse", None, "Centipede"]})
>>> table = pa.Table.from_pandas(df)
>>> table.num_rows
4
"""
return self.table.num_rows()
@property
def nbytes(self):
"""
Total number of bytes consumed by the elements of the table.
In other words, the sum of bytes from all buffer ranges referenced.
Unlike `get_total_buffer_size` this method will account for array
offsets.
If buffers are shared between arrays then the shared
portion will only be counted multiple times.
The dictionary of dictionary arrays will always be counted in their
entirety even if the array only references a portion of the dictionary.
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [None, 4, 5, None],
... 'animals': ["Flamingo", "Horse", None, "Centipede"]})
>>> table = pa.Table.from_pandas(df)
>>> table.nbytes
72
"""
self._assert_cpu()
cdef:
CResult[int64_t] c_res_buffer
with nogil:
c_res_buffer = ReferencedBufferSize(deref(self.table))
size = GetResultValue(c_res_buffer)
return size
def get_total_buffer_size(self):
"""
The sum of bytes in each buffer referenced by the table.
An array may only reference a portion of a buffer.
This method will overestimate in this case and return the
byte size of the entire buffer.
If a buffer is referenced multiple times then it will
only be counted once.
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [None, 4, 5, None],
... 'animals': ["Flamingo", "Horse", None, "Centipede"]})
>>> table = pa.Table.from_pandas(df)
>>> table.get_total_buffer_size()
76
"""
self._assert_cpu()
cdef:
int64_t total_buffer_size
total_buffer_size = TotalBufferSize(deref(self.table))
return total_buffer_size
def __sizeof__(self):
return super(Table, self).__sizeof__() + self.nbytes
def add_column(self, int i, field_, column):
"""
Add column to Table at position.
A new table is returned with the column added, the original table
object is left unchanged.
Parameters
----------
i : int
Index to place the column at.
field_ : str or Field
If a string is passed then the type is deduced from the column
data.
column : Array, list of Array, or values coercible to arrays
Column data.
Returns
-------
Table
New table with the passed column added.
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> table = pa.Table.from_pandas(df)
Add column:
>>> year = [2021, 2022, 2019, 2021]
>>> table.add_column(0,"year", [year])
pyarrow.Table
year: int64
n_legs: int64
animals: string
----
year: [[2021,2022,2019,2021]]
n_legs: [[2,4,5,100]]
animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
Original table is left unchanged:
>>> table
pyarrow.Table
n_legs: int64
animals: string
----
n_legs: [[2,4,5,100]]
animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
"""
cdef:
shared_ptr[CTable] c_table
Field c_field
ChunkedArray c_arr
if isinstance(column, ChunkedArray):
c_arr = column
else:
c_arr = chunked_array(column)
if isinstance(field_, Field):
c_field = field_
else:
c_field = field(field_, c_arr.type)
with nogil:
c_table = GetResultValue(self.table.AddColumn(
i, c_field.sp_field, c_arr.sp_chunked_array))
return pyarrow_wrap_table(c_table)
def remove_column(self, int i):
"""
Create new Table with the indicated column removed.
Parameters
----------
i : int
Index of column to remove.
Returns
-------
Table
New table without the column.
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> table = pa.Table.from_pandas(df)
>>> table.remove_column(1)
pyarrow.Table
n_legs: int64
----
n_legs: [[2,4,5,100]]
"""
cdef shared_ptr[CTable] c_table
with nogil:
c_table = GetResultValue(self.table.RemoveColumn(i))
return pyarrow_wrap_table(c_table)
def set_column(self, int i, field_, column):
"""
Replace column in Table at position.
Parameters
----------
i : int
Index to place the column at.
field_ : str or Field
If a string is passed then the type is deduced from the column
data.
column : Array, list of Array, or values coercible to arrays
Column data.
Returns
-------
Table
New table with the passed column set.
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> table = pa.Table.from_pandas(df)
Replace a column:
>>> year = [2021, 2022, 2019, 2021]
>>> table.set_column(1,'year', [year])
pyarrow.Table
n_legs: int64
year: int64
----
n_legs: [[2,4,5,100]]
year: [[2021,2022,2019,2021]]
"""
cdef:
shared_ptr[CTable] c_table
Field c_field
ChunkedArray c_arr
if isinstance(column, ChunkedArray):
c_arr = column
else:
c_arr = chunked_array(column)
if isinstance(field_, Field):
c_field = field_
else:
c_field = field(field_, c_arr.type)
with nogil:
c_table = GetResultValue(self.table.SetColumn(
i, c_field.sp_field, c_arr.sp_chunked_array))
return pyarrow_wrap_table(c_table)
def rename_columns(self, names):
"""
Create new table with columns renamed to provided names.
Parameters
----------
names : list[str] or dict[str, str]
List of new column names or mapping of old column names to new column names.
If a mapping of old to new column names is passed, then all columns which are
found to match a provided old column name will be renamed to the new column name.
If any column names are not found in the mapping, a KeyError will be raised.
Raises
------
KeyError
If any of the column names passed in the names mapping do not exist.
Returns
-------
Table
Examples
--------
>>> import pyarrow as pa
>>> import pandas as pd
>>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> table = pa.Table.from_pandas(df)
>>> new_names = ["n", "name"]
>>> table.rename_columns(new_names)
pyarrow.Table
n: int64
name: string
----
n: [[2,4,5,100]]
name: [["Flamingo","Horse","Brittle stars","Centipede"]]
>>> new_names = {"n_legs": "n", "animals": "name"}
>>> table.rename_columns(new_names)
pyarrow.Table
n: int64
name: string
----
n: [[2,4,5,100]]
name: [["Flamingo","Horse","Brittle stars","Centipede"]]
"""
cdef:
shared_ptr[CTable] c_table
vector[c_string] c_names
if isinstance(names, (list, tuple)):
for name in names:
c_names.push_back(tobytes(name))
elif isinstance(names, dict):
idx_to_new_name = {}
for name, new_name in names.items():
indices = self.schema.get_all_field_indices(name)
if not indices:
raise KeyError("Column {!r} not found".format(name))
for index in indices:
idx_to_new_name[index] = new_name
for i in range(self.num_columns):
c_names.push_back(tobytes(idx_to_new_name.get(i, self.schema[i].name)))
else:
raise TypeError(f"names must be a list or dict not {type(names)!r}")
with nogil:
c_table = GetResultValue(self.table.RenameColumns(move(c_names)))
return pyarrow_wrap_table(c_table)
def drop(self, columns):
"""
Drop one or more columns and return a new table.
Alias of Table.drop_columns, but kept for backwards compatibility.
Parameters
----------
columns : str or list[str]
Field name(s) referencing existing column(s).
Returns
-------
Table
New table without the column(s).
"""
return self.drop_columns(columns)
def group_by(self, keys, use_threads=True):
"""
Declare a grouping over the columns of the table.
Resulting grouping can then be used to perform aggregations
with a subsequent ``aggregate()`` method.
Parameters
----------
keys : str or list[str]
Name of the columns that should be used as the grouping key.
use_threads : bool, default True
Whether to use multithreading or not. When set to True (the
default), no stable ordering of the output is guaranteed.
Returns
-------
TableGroupBy
See Also
--------
TableGroupBy.aggregate
Examples
--------
>>> import pandas as pd
>>> import pyarrow as pa
>>> df = pd.DataFrame({'year': [2020, 2022, 2021, 2022, 2019, 2021],
... 'n_legs': [2, 2, 4, 4, 5, 100],
... 'animal': ["Flamingo", "Parrot", "Dog", "Horse",
... "Brittle stars", "Centipede"]})
>>> table = pa.Table.from_pandas(df)
>>> table.group_by('year').aggregate([('n_legs', 'sum')])
pyarrow.Table
year: int64
n_legs_sum: int64
----
year: [[2020,2022,2021,2019]]
n_legs_sum: [[2,6,104,5]]
"""
self._assert_cpu()
return TableGroupBy(self, keys, use_threads=use_threads)
def join(self, right_table, keys, right_keys=None, join_type="left outer",
left_suffix=None, right_suffix=None, coalesce_keys=True,
use_threads=True):
"""
Perform a join between this table and another one.
Result of the join will be a new Table, where further
operations can be applied.
Parameters
----------
right_table : Table
The table to join to the current one, acting as the right table
in the join operation.
keys : str or list[str]
The columns from current table that should be used as keys
of the join operation left side.
right_keys : str or list[str], default None
The columns from the right_table that should be used as keys
on the join operation right side.
When ``None`` use the same key names as the left table.
join_type : str, default "left outer"
The kind of join that should be performed, one of
("left semi", "right semi", "left anti", "right anti",
"inner", "left outer", "right outer", "full outer")
left_suffix : str, default None
Which suffix to add to left column names. This prevents confusion
when the columns in left and right tables have colliding names.
right_suffix : str, default None
Which suffix to add to the right column names. This prevents confusion
when the columns in left and right tables have colliding names.
coalesce_keys : bool, default True
If the duplicated keys should be omitted from one of the sides
in the join result.
use_threads : bool, default True
Whether to use multithreading or not.
Returns
-------
Table
Examples
--------
>>> import pandas as pd
>>> import pyarrow as pa
>>> df1 = pd.DataFrame({'id': [1, 2, 3],
... 'year': [2020, 2022, 2019]})
>>> df2 = pd.DataFrame({'id': [3, 4],
... 'n_legs': [5, 100],
... 'animal': ["Brittle stars", "Centipede"]})
>>> t1 = pa.Table.from_pandas(df1)
>>> t2 = pa.Table.from_pandas(df2)
Left outer join:
>>> t1.join(t2, 'id').combine_chunks().sort_by('year')
pyarrow.Table
id: int64
year: int64
n_legs: int64
animal: string
----
id: [[3,1,2]]
year: [[2019,2020,2022]]
n_legs: [[5,null,null]]
animal: [["Brittle stars",null,null]]
Full outer join:
>>> t1.join(t2, 'id', join_type="full outer").combine_chunks().sort_by('year')
pyarrow.Table
id: int64
year: int64
n_legs: int64
animal: string
----
id: [[3,1,2,4]]
year: [[2019,2020,2022,null]]
n_legs: [[5,null,null,100]]
animal: [["Brittle stars",null,null,"Centipede"]]
Right outer join:
>>> t1.join(t2, 'id', join_type="right outer").combine_chunks().sort_by('year')
pyarrow.Table
year: int64
id: int64
n_legs: int64
animal: string
----
year: [[2019,null]]
id: [[3,4]]
n_legs: [[5,100]]
animal: [["Brittle stars","Centipede"]]
Right anti join
>>> t1.join(t2, 'id', join_type="right anti")
pyarrow.Table
id: int64
n_legs: int64
animal: string
----
id: [[4]]
n_legs: [[100]]
animal: [["Centipede"]]
"""
self._assert_cpu()
if right_keys is None:
right_keys = keys
return _pac()._perform_join(
join_type, self, keys, right_table, right_keys,
left_suffix=left_suffix, right_suffix=right_suffix,
use_threads=use_threads, coalesce_keys=coalesce_keys,
output_type=Table
)
def join_asof(self, right_table, on, by, tolerance, right_on=None, right_by=None):
"""
Perform an asof join between this table and another one.
This is similar to a left-join except that we match on nearest key rather
than equal keys. Both tables must be sorted by the key. This type of join
is most useful for time series data that are not perfectly aligned.
Optionally match on equivalent keys with "by" before searching with "on".
Result of the join will be a new Table, where further
operations can be applied.
Parameters
----------
right_table : Table
The table to join to the current one, acting as the right table
in the join operation.
on : str
The column from current table that should be used as the "on" key
of the join operation left side.
An inexact match is used on the "on" key, i.e. a row is considered a
match if and only if left_on - tolerance <= right_on <= left_on.
The input dataset must be sorted by the "on" key. Must be a single
field of a common type.
Currently, the "on" key must be an integer, date, or timestamp type.
by : str or list[str]
The columns from current table that should be used as the keys
of the join operation left side. The join operation is then done
only for the matches in these columns.
tolerance : int
The tolerance for inexact "on" key matching. A right row is considered
a match with the left row ``right.on - left.on <= tolerance``. The
``tolerance`` may be:
- negative, in which case a past-as-of-join occurs;
- or positive, in which case a future-as-of-join occurs;
- or zero, in which case an exact-as-of-join occurs.
The tolerance is interpreted in the same units as the "on" key.
right_on : str or list[str], default None
The columns from the right_table that should be used as the on key
on the join operation right side.
When ``None`` use the same key name as the left table.
right_by : str or list[str], default None
The columns from the right_table that should be used as keys
on the join operation right side.
When ``None`` use the same key names as the left table.
Returns
-------
Table
Example
--------
>>> import pyarrow as pa
>>> t1 = pa.table({'id': [1, 3, 2, 3, 3],
... 'year': [2020, 2021, 2022, 2022, 2023]})
>>> t2 = pa.table({'id': [3, 4],
... 'year': [2020, 2021],
... 'n_legs': [5, 100],
... 'animal': ["Brittle stars", "Centipede"]})
>>> t1.join_asof(t2, on='year', by='id', tolerance=-2)
pyarrow.Table
id: int64
year: int64
n_legs: int64
animal: string
----
id: [[1,3,2,3,3]]
year: [[2020,2021,2022,2022,2023]]
n_legs: [[null,5,null,5,null]]
animal: [[null,"Brittle stars",null,"Brittle stars",null]]
"""
self._assert_cpu()
if right_on is None:
right_on = on
if right_by is None:
right_by = by
return _pac()._perform_join_asof(self, on, by,
right_table, right_on, right_by,
tolerance, output_type=Table)
def __arrow_c_stream__(self, requested_schema=None):
"""
Export the table as an Arrow C stream PyCapsule.
Parameters
----------
requested_schema : PyCapsule, default None
The schema to which the stream should be casted, passed as a
PyCapsule containing a C ArrowSchema representation of the
requested schema.
Currently, this is not supported and will raise a
NotImplementedError if the schema doesn't match the current schema.
Returns
-------
PyCapsule
"""
self._assert_cpu()
return self.to_reader().__arrow_c_stream__(requested_schema)
@property
def is_cpu(self):
"""
Whether all ChunkedArrays are CPU-accessible.
"""
if not self._init_is_cpu:
self._is_cpu = all(c.is_cpu for c in self.itercolumns())
self._init_is_cpu = True
return self._is_cpu
cdef void _assert_cpu(self) except *:
if not self.is_cpu:
raise NotImplementedError("Implemented only for data on CPU device")
def _reconstruct_table(arrays, schema):
"""
Internal: reconstruct pa.Table from pickled components.
"""
return Table.from_arrays(arrays, schema=schema)
def record_batch(data, names=None, schema=None, metadata=None):
"""
Create a pyarrow.RecordBatch from another Python data structure or sequence
of arrays.
Parameters
----------
data : dict, list, pandas.DataFrame, Arrow-compatible table
A mapping of strings to Arrays or Python lists, a list of Arrays,
a pandas DataFame, or any tabular object implementing the
Arrow PyCapsule Protocol (has an ``__arrow_c_array__`` or
``__arrow_c_device_array__`` method).
names : list, default None
Column names if list of arrays passed as data. Mutually exclusive with
'schema' argument.
schema : Schema, default None
The expected schema of the RecordBatch. If not passed, will be inferred
from the data. Mutually exclusive with 'names' argument.
metadata : dict or Mapping, default None
Optional metadata for the schema (if schema not passed).
Returns
-------
RecordBatch
See Also
--------
RecordBatch.from_arrays, RecordBatch.from_pandas, table
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.array([2, 2, 4, 4, 5, 100])
>>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"])
>>> names = ["n_legs", "animals"]
Construct a RecordBatch from a python dictionary:
>>> pa.record_batch({"n_legs": n_legs, "animals": animals})
pyarrow.RecordBatch
n_legs: int64
animals: string
----
n_legs: [2,2,4,4,5,100]
animals: ["Flamingo","Parrot","Dog","Horse","Brittle stars","Centipede"]
>>> pa.record_batch({"n_legs": n_legs, "animals": animals}).to_pandas()
n_legs animals
0 2 Flamingo
1 2 Parrot
2 4 Dog
3 4 Horse
4 5 Brittle stars
5 100 Centipede
Creating a RecordBatch from a list of arrays with names:
>>> pa.record_batch([n_legs, animals], names=names)
pyarrow.RecordBatch
n_legs: int64
animals: string
----
n_legs: [2,2,4,4,5,100]
animals: ["Flamingo","Parrot","Dog","Horse","Brittle stars","Centipede"]
Creating a RecordBatch from a list of arrays with names and metadata:
>>> my_metadata={"n_legs": "How many legs does an animal have?"}
>>> pa.record_batch([n_legs, animals],
... names=names,
... metadata = my_metadata)
pyarrow.RecordBatch
n_legs: int64
animals: string
----
n_legs: [2,2,4,4,5,100]
animals: ["Flamingo","Parrot","Dog","Horse","Brittle stars","Centipede"]
>>> pa.record_batch([n_legs, animals],
... names=names,
... metadata = my_metadata).schema
n_legs: int64
animals: string
-- schema metadata --
n_legs: 'How many legs does an animal have?'
Creating a RecordBatch from a pandas DataFrame:
>>> import pandas as pd
>>> df = pd.DataFrame({'year': [2020, 2022, 2021, 2022],
... 'month': [3, 5, 7, 9],
... 'day': [1, 5, 9, 13],
... 'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> pa.record_batch(df)
pyarrow.RecordBatch
year: int64
month: int64
day: int64
n_legs: int64
animals: string
----
year: [2020,2022,2021,2022]
month: [3,5,7,9]
day: [1,5,9,13]
n_legs: [2,4,5,100]
animals: ["Flamingo","Horse","Brittle stars","Centipede"]
>>> pa.record_batch(df).to_pandas()
year month day n_legs animals
0 2020 3 1 2 Flamingo
1 2022 5 5 4 Horse
2 2021 7 9 5 Brittle stars
3 2022 9 13 100 Centipede
Creating a RecordBatch from a pandas DataFrame with schema:
>>> my_schema = pa.schema([
... pa.field('n_legs', pa.int64()),
... pa.field('animals', pa.string())],
... metadata={"n_legs": "Number of legs per animal"})
>>> pa.record_batch(df, my_schema).schema
n_legs: int64
animals: string
-- schema metadata --
n_legs: 'Number of legs per animal'
pandas: ...
>>> pa.record_batch(df, my_schema).to_pandas()
n_legs animals
0 2 Flamingo
1 4 Horse
2 5 Brittle stars
3 100 Centipede
"""
# accept schema as first argument for backwards compatibility / usability
if isinstance(names, Schema) and schema is None:
schema = names
names = None
if isinstance(data, (list, tuple)):
return RecordBatch.from_arrays(data, names=names, schema=schema,
metadata=metadata)
elif isinstance(data, dict):
if names is not None:
raise ValueError(
"The 'names' argument is not valid when passing a dictionary")
return RecordBatch.from_pydict(data, schema=schema, metadata=metadata)
elif hasattr(data, "__arrow_c_device_array__"):
if schema is not None:
requested_schema = schema.__arrow_c_schema__()
else:
requested_schema = None
schema_capsule, array_capsule = data.__arrow_c_device_array__(requested_schema)
batch = RecordBatch._import_from_c_device_capsule(schema_capsule, array_capsule)
if schema is not None and batch.schema != schema:
# __arrow_c_device_array__ coerces schema with best effort, so we might
# need to cast it if the producer wasn't able to cast to exact schema.
batch = batch.cast(schema)
return batch
elif hasattr(data, "__arrow_c_array__"):
if schema is not None:
requested_schema = schema.__arrow_c_schema__()
else:
requested_schema = None
schema_capsule, array_capsule = data.__arrow_c_array__(requested_schema)
batch = RecordBatch._import_from_c_capsule(schema_capsule, array_capsule)
if schema is not None and batch.schema != schema:
# __arrow_c_array__ coerces schema with best effort, so we might
# need to cast it if the producer wasn't able to cast to exact schema.
batch = batch.cast(schema)
return batch
elif _pandas_api.is_data_frame(data):
return RecordBatch.from_pandas(data, schema=schema)
else:
raise TypeError("Expected pandas DataFrame or list of arrays")
def table(data, names=None, schema=None, metadata=None, nthreads=None):
"""
Create a pyarrow.Table from a Python data structure or sequence of arrays.
Parameters
----------
data : dict, list, pandas.DataFrame, Arrow-compatible table
A mapping of strings to Arrays or Python lists, a list of arrays or
chunked arrays, a pandas DataFame, or any tabular object implementing
the Arrow PyCapsule Protocol (has an ``__arrow_c_array__``,
``__arrow_c_device_array__`` or ``__arrow_c_stream__`` method).
names : list, default None
Column names if list of arrays passed as data. Mutually exclusive with
'schema' argument.
schema : Schema, default None
The expected schema of the Arrow Table. If not passed, will be inferred
from the data. Mutually exclusive with 'names' argument.
If passed, the output will have exactly this schema (raising an error
when columns are not found in the data and ignoring additional data not
specified in the schema, when data is a dict or DataFrame).
metadata : dict or Mapping, default None
Optional metadata for the schema (if schema not passed).
nthreads : int, default None
For pandas.DataFrame inputs: if greater than 1, convert columns to
Arrow in parallel using indicated number of threads. By default,
this follows :func:`pyarrow.cpu_count` (may use up to system CPU count
threads).
Returns
-------
Table
See Also
--------
Table.from_arrays, Table.from_pandas, Table.from_pydict
Examples
--------
>>> import pyarrow as pa
>>> n_legs = pa.array([2, 4, 5, 100])
>>> animals = pa.array(["Flamingo", "Horse", "Brittle stars", "Centipede"])
>>> names = ["n_legs", "animals"]
Construct a Table from a python dictionary:
>>> pa.table({"n_legs": n_legs, "animals": animals})
pyarrow.Table
n_legs: int64
animals: string
----
n_legs: [[2,4,5,100]]
animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
Construct a Table from arrays:
>>> pa.table([n_legs, animals], names=names)
pyarrow.Table
n_legs: int64
animals: string
----
n_legs: [[2,4,5,100]]
animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
Construct a Table from arrays with metadata:
>>> my_metadata={"n_legs": "Number of legs per animal"}
>>> pa.table([n_legs, animals], names=names, metadata = my_metadata).schema
n_legs: int64
animals: string
-- schema metadata --
n_legs: 'Number of legs per animal'
Construct a Table from pandas DataFrame:
>>> import pandas as pd
>>> df = pd.DataFrame({'year': [2020, 2022, 2019, 2021],
... 'n_legs': [2, 4, 5, 100],
... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
>>> pa.table(df)
pyarrow.Table
year: int64
n_legs: int64
animals: string
----
year: [[2020,2022,2019,2021]]
n_legs: [[2,4,5,100]]
animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
Construct a Table from pandas DataFrame with pyarrow schema:
>>> my_schema = pa.schema([
... pa.field('n_legs', pa.int64()),
... pa.field('animals', pa.string())],
... metadata={"n_legs": "Number of legs per animal"})
>>> pa.table(df, my_schema).schema
n_legs: int64
animals: string
-- schema metadata --
n_legs: 'Number of legs per animal'
pandas: '{"index_columns": [], "column_indexes": [{"name": null, ...
Construct a Table from chunked arrays:
>>> n_legs = pa.chunked_array([[2, 2, 4], [4, 5, 100]])
>>> animals = pa.chunked_array([["Flamingo", "Parrot", "Dog"], ["Horse", "Brittle stars", "Centipede"]])
>>> table = pa.table([n_legs, animals], names=names)
>>> table
pyarrow.Table
n_legs: int64
animals: string
----
n_legs: [[2,2,4],[4,5,100]]
animals: [["Flamingo","Parrot","Dog"],["Horse","Brittle stars","Centipede"]]
"""
# accept schema as first argument for backwards compatibility / usability
if isinstance(names, Schema) and schema is None:
schema = names
names = None
if isinstance(data, (list, tuple)):
return Table.from_arrays(data, names=names, schema=schema,
metadata=metadata)
elif isinstance(data, dict):
if names is not None:
raise ValueError(
"The 'names' argument is not valid when passing a dictionary")
return Table.from_pydict(data, schema=schema, metadata=metadata)
elif _pandas_api.is_data_frame(data):
if names is not None or metadata is not None:
raise ValueError(
"The 'names' and 'metadata' arguments are not valid when "
"passing a pandas DataFrame")
return Table.from_pandas(data, schema=schema, nthreads=nthreads)
elif hasattr(data, "__arrow_c_stream__"):
if names is not None or metadata is not None:
raise ValueError(
"The 'names' and 'metadata' arguments are not valid when "
"using Arrow PyCapsule Interface")
if schema is not None:
requested = schema.__arrow_c_schema__()
else:
requested = None
capsule = data.__arrow_c_stream__(requested)
reader = RecordBatchReader._import_from_c_capsule(capsule)
table = reader.read_all()
if schema is not None and table.schema != schema:
# __arrow_c_array__ coerces schema with best effort, so we might
# need to cast it if the producer wasn't able to cast to exact schema.
table = table.cast(schema)
return table
elif hasattr(data, "__arrow_c_array__") or hasattr(data, "__arrow_c_device_array__"):
if names is not None or metadata is not None:
raise ValueError(
"The 'names' and 'metadata' arguments are not valid when "
"using Arrow PyCapsule Interface")
batch = record_batch(data, schema)
return Table.from_batches([batch])
else:
raise TypeError(
"Expected pandas DataFrame, python dictionary or list of arrays")
def concat_tables(tables, MemoryPool memory_pool=None, str promote_options="none", **kwargs):
"""
Concatenate pyarrow.Table objects.
If promote_options="none", a zero-copy concatenation will be performed. The schemas
of all the Tables must be the same (except the metadata), otherwise an
exception will be raised. The result Table will share the metadata with the
first table.
If promote_options="default", any null type arrays will be casted to the type of other
arrays in the column of the same name. If a table is missing a particular
field, null values of the appropriate type will be generated to take the
place of the missing field. The new schema will share the metadata with the
first table. Each field in the new schema will share the metadata with the
first table which has the field defined. Note that type promotions may
involve additional allocations on the given ``memory_pool``.
If promote_options="permissive", the behavior of default plus types will be promoted
to the common denominator that fits all the fields.
Parameters
----------
tables : iterable of pyarrow.Table objects
Pyarrow tables to concatenate into a single Table.
memory_pool : MemoryPool, default None
For memory allocations, if required, otherwise use default pool.
promote_options : str, default none
Accepts strings "none", "default" and "permissive".
**kwargs : dict, optional
Examples
--------
>>> import pyarrow as pa
>>> t1 = pa.table([
... pa.array([2, 4, 5, 100]),
... pa.array(["Flamingo", "Horse", "Brittle stars", "Centipede"])
... ], names=['n_legs', 'animals'])
>>> t2 = pa.table([
... pa.array([2, 4]),
... pa.array(["Parrot", "Dog"])
... ], names=['n_legs', 'animals'])
>>> pa.concat_tables([t1,t2])
pyarrow.Table
n_legs: int64
animals: string
----
n_legs: [[2,4,5,100],[2,4]]
animals: [["Flamingo","Horse","Brittle stars","Centipede"],["Parrot","Dog"]]
"""
cdef:
vector[shared_ptr[CTable]] c_tables
shared_ptr[CTable] c_result_table
CMemoryPool* pool = maybe_unbox_memory_pool(memory_pool)
Table table
CConcatenateTablesOptions options = (
CConcatenateTablesOptions.Defaults())
if "promote" in kwargs:
warnings.warn(
"promote has been superseded by promote_options='default'.",
FutureWarning, stacklevel=2)
if kwargs['promote'] is True:
promote_options = "default"
for table in tables:
c_tables.push_back(table.sp_table)
if promote_options == "permissive":
options.field_merge_options = CField.CMergeOptions.Permissive()
elif promote_options in {"default", "none"}:
options.field_merge_options = CField.CMergeOptions.Defaults()
else:
raise ValueError(f"Invalid promote options: {promote_options}")
with nogil:
options.unify_schemas = promote_options != "none"
c_result_table = GetResultValue(
ConcatenateTables(c_tables, options, pool))
return pyarrow_wrap_table(c_result_table)
def concat_batches(recordbatches, MemoryPool memory_pool=None):
"""
Concatenate pyarrow.RecordBatch objects.
All recordbatches must share the same Schema,
the operation implies a copy of the data to merge
the arrays of the different RecordBatches.
Parameters
----------
recordbatches : iterable of pyarrow.RecordBatch objects
Pyarrow record batches to concatenate into a single RecordBatch.
memory_pool : MemoryPool, default None
For memory allocations, if required, otherwise use default pool.
Examples
--------
>>> import pyarrow as pa
>>> t1 = pa.record_batch([
... pa.array([2, 4, 5, 100]),
... pa.array(["Flamingo", "Horse", "Brittle stars", "Centipede"])
... ], names=['n_legs', 'animals'])
>>> t2 = pa.record_batch([
... pa.array([2, 4]),
... pa.array(["Parrot", "Dog"])
... ], names=['n_legs', 'animals'])
>>> pa.concat_batches([t1,t2])
pyarrow.RecordBatch
n_legs: int64
animals: string
----
n_legs: [2,4,5,100,2,4]
animals: ["Flamingo","Horse","Brittle stars","Centipede","Parrot","Dog"]
"""
cdef:
vector[shared_ptr[CRecordBatch]] c_recordbatches
shared_ptr[CRecordBatch] c_result_recordbatch
RecordBatch recordbatch
CMemoryPool* pool = maybe_unbox_memory_pool(memory_pool)
for recordbatch in recordbatches:
c_recordbatches.push_back(recordbatch.sp_batch)
with nogil:
c_result_recordbatch = GetResultValue(
ConcatenateRecordBatches(c_recordbatches, pool))
return pyarrow_wrap_batch(c_result_recordbatch)
def _from_pydict(cls, mapping, schema, metadata):
"""
Construct a Table/RecordBatch from Arrow arrays or columns.
Parameters
----------
cls : Class Table/RecordBatch
mapping : dict or Mapping
A mapping of strings to Arrays or Python lists.
schema : Schema, default None
If not passed, will be inferred from the Mapping values.
metadata : dict or Mapping, default None
Optional metadata for the schema (if inferred).
Returns
-------
Table/RecordBatch
"""
arrays = []
if schema is None:
names = []
for k, v in mapping.items():
names.append(k)
arrays.append(asarray(v))
return cls.from_arrays(arrays, names, metadata=metadata)
elif isinstance(schema, Schema):
for field in schema:
try:
v = mapping[field.name]
except KeyError:
try:
v = mapping[tobytes(field.name)]
except KeyError:
present = mapping.keys()
missing = [n for n in schema.names if n not in present]
raise KeyError(
"The passed mapping doesn't contain the "
"following field(s) of the schema: {}".
format(', '.join(missing))
)
arrays.append(asarray(v, type=field.type))
# Will raise if metadata is not None
return cls.from_arrays(arrays, schema=schema, metadata=metadata)
else:
raise TypeError('Schema must be an instance of pyarrow.Schema')
def _from_pylist(cls, mapping, schema, metadata):
"""
Construct a Table/RecordBatch from list of rows / dictionaries.
Parameters
----------
cls : Class Table/RecordBatch
mapping : list of dicts of rows
A mapping of strings to row values.
schema : Schema, default None
If not passed, will be inferred from the first row of the
mapping values.
metadata : dict or Mapping, default None
Optional metadata for the schema (if inferred).
Returns
-------
Table/RecordBatch
"""
arrays = []
if schema is None:
names = []
if mapping:
names = list(mapping[0].keys())
for n in names:
v = [row[n] if n in row else None for row in mapping]
arrays.append(v)
return cls.from_arrays(arrays, names, metadata=metadata)
else:
if isinstance(schema, Schema):
for n in schema.names:
v = [row[n] if n in row else None for row in mapping]
arrays.append(v)
# Will raise if metadata is not None
return cls.from_arrays(arrays, schema=schema, metadata=metadata)
else:
raise TypeError('Schema must be an instance of pyarrow.Schema')
class TableGroupBy:
"""
A grouping of columns in a table on which to perform aggregations.
Parameters
----------
table : pyarrow.Table
Input table to execute the aggregation on.
keys : str or list[str]
Name of the grouped columns.
use_threads : bool, default True
Whether to use multithreading or not. When set to True (the default),
no stable ordering of the output is guaranteed.
Examples
--------
>>> import pyarrow as pa
>>> t = pa.table([
... pa.array(["a", "a", "b", "b", "c"]),
... pa.array([1, 2, 3, 4, 5]),
... ], names=["keys", "values"])
Grouping of columns:
>>> pa.TableGroupBy(t,"keys")
<pyarrow.lib.TableGroupBy object at ...>
Perform aggregations:
>>> pa.TableGroupBy(t,"keys").aggregate([("values", "sum")])
pyarrow.Table
keys: string
values_sum: int64
----
keys: [["a","b","c"]]
values_sum: [[3,7,5]]
"""
def __init__(self, table, keys, use_threads=True):
if isinstance(keys, str):
keys = [keys]
self._table = table
self.keys = keys
self._use_threads = use_threads
def aggregate(self, aggregations):
"""
Perform an aggregation over the grouped columns of the table.
Parameters
----------
aggregations : list[tuple(str, str)] or \
list[tuple(str, str, FunctionOptions)]
List of tuples, where each tuple is one aggregation specification
and consists of: aggregation column name followed
by function name and optionally aggregation function option.
Pass empty list to get a single row for each group.
The column name can be a string, an empty list or a list of
column names, for unary, nullary and n-ary aggregation functions
respectively.
For the list of function names and respective aggregation
function options see :ref:`py-grouped-aggrs`.
Returns
-------
Table
Results of the aggregation functions.
Examples
--------
>>> import pyarrow as pa
>>> t = pa.table([
... pa.array(["a", "a", "b", "b", "c"]),
... pa.array([1, 2, 3, 4, 5]),
... ], names=["keys", "values"])
Sum the column "values" over the grouped column "keys":
>>> t.group_by("keys").aggregate([("values", "sum")])
pyarrow.Table
keys: string
values_sum: int64
----
keys: [["a","b","c"]]
values_sum: [[3,7,5]]
Count the rows over the grouped column "keys":
>>> t.group_by("keys").aggregate([([], "count_all")])
pyarrow.Table
keys: string
count_all: int64
----
keys: [["a","b","c"]]
count_all: [[2,2,1]]
Do multiple aggregations:
>>> t.group_by("keys").aggregate([
... ("values", "sum"),
... ("keys", "count")
... ])
pyarrow.Table
keys: string
values_sum: int64
keys_count: int64
----
keys: [["a","b","c"]]
values_sum: [[3,7,5]]
keys_count: [[2,2,1]]
Count the number of non-null values for column "values"
over the grouped column "keys":
>>> import pyarrow.compute as pc
>>> t.group_by(["keys"]).aggregate([
... ("values", "count", pc.CountOptions(mode="only_valid"))
... ])
pyarrow.Table
keys: string
values_count: int64
----
keys: [["a","b","c"]]
values_count: [[2,2,1]]
Get a single row for each group in column "keys":
>>> t.group_by("keys").aggregate([])
pyarrow.Table
keys: string
----
keys: [["a","b","c"]]
"""
group_by_aggrs = []
for aggr in aggregations:
# Set opt to None if not specified
if len(aggr) == 2:
target, func = aggr
opt = None
else:
target, func, opt = aggr
# Ensure target is a list
if not isinstance(target, (list, tuple)):
target = [target]
# Ensure aggregate function is hash_ if needed
if len(self.keys) > 0 and not func.startswith("hash_"):
func = "hash_" + func
if len(self.keys) == 0 and func.startswith("hash_"):
func = func[5:]
# Determine output field name
func_nohash = func if not func.startswith("hash_") else func[5:]
if len(target) == 0:
aggr_name = func_nohash
else:
aggr_name = "_".join(target) + "_" + func_nohash
group_by_aggrs.append((target, func, opt, aggr_name))
return _pac()._group_by(
self._table, group_by_aggrs, self.keys, use_threads=self._use_threads
)
|