Debian Codegraph @

docs/source/array-stack.rst

raw
1 Stack, Concatenate, and Block
2 =============================
3
4 Often we have many arrays stored on disk that we want to stack together and
5 think of as one large array. This is common with geospatial data in which we
6 might have many HDF5/NetCDF files on disk, one for every day, but we want to do
7 operations that span multiple days.
8
9 To solve this problem, we use the functions ``da.stack``, ``da.concatenate``,
10 and ``da.block``.
11
12 Stack
13 -----
14
15 We stack many existing Dask arrays into a new array, creating a new dimension
16 as we go.
17
18 .. code-block:: python
19
20 >>> import dask.array as da
21
22 >>> arr0 = da.from_array(np.zeros((3, 4)), chunks=(1, 2))
23 >>> arr1 = da.from_array(np.ones((3, 4)), chunks=(1, 2))
24
25 >>> data = [arr0, arr1]
26
27 >>> x = da.stack(data, axis=0)
28 >>> x.shape
29 (2, 3, 4)
30
31 >>> da.stack(data, axis=1).shape
32 (3, 2, 4)
33
34 >>> da.stack(data, axis=-1).shape
35 (3, 4, 2)
36
37 This creates a new dimension with length equal to the number of slices
38
39 Concatenate
40 -----------
41
42 We concatenate existing arrays into a new array, extending them along an
43 existing dimension
44
45 .. code-block:: python
46
47 >>> import dask.array as da
48 >>> import numpy as np
49
50 >>> arr0 = da.from_array(np.zeros((3, 4)), chunks=(1, 2))
51 >>> arr1 = da.from_array(np.ones((3, 4)), chunks=(1, 2))
52
53 >>> data = [arr0, arr1]
54
55 >>> x = da.concatenate(data, axis=0)
56 >>> x.shape
57 (6, 4)
58
59 >>> da.concatenate(data, axis=1).shape
60 (3, 8)
61
62 Block
63 -----
64
65 We can handle a larger variety of cases with ``da.block`` as it allows
66 concatenation to be applied over multiple dimensions at once. This is useful if
67 your chunks tile a space, for example if small squares tile a larger 2-D plane.
68
69 .. code-block:: python
70
71 >>> import dask.array as da
72 >>> import numpy as np
73
74 >>> arr0 = da.from_array(np.zeros((3, 4)), chunks=(1, 2))
75 >>> arr1 = da.from_array(np.ones((3, 4)), chunks=(1, 2))
76
77 >>> data = [
78 ... [arr0, arr1],
79 ... [arr1, arr0]
80 ... ]
81
82 >>> x = da.block(data)
83 >>> x.shape
84 (6, 8)