Stack arrays along a new axis Given a sequence of dask arrays, form a new dask array by stacking them along a new dimension (axis=0 by default) Parameters ---------- seq: list of dask.arrays axis: int Dimension along which to align all of the arrays allow_u
(seq, axis=0, allow_unknown_chunksizes=False)
| 5305 | |
| 5306 | |
| 5307 | def stack(seq, axis=0, allow_unknown_chunksizes=False): |
| 5308 | """ |
| 5309 | Stack arrays along a new axis |
| 5310 | |
| 5311 | Given a sequence of dask arrays, form a new dask array by stacking them |
| 5312 | along a new dimension (axis=0 by default) |
| 5313 | |
| 5314 | Parameters |
| 5315 | ---------- |
| 5316 | seq: list of dask.arrays |
| 5317 | axis: int |
| 5318 | Dimension along which to align all of the arrays |
| 5319 | allow_unknown_chunksizes: bool |
| 5320 | Allow unknown chunksizes, such as come from converting from dask |
| 5321 | dataframes. Dask.array is unable to verify that chunks line up. If |
| 5322 | data comes from differently aligned sources then this can cause |
| 5323 | unexpected results. |
| 5324 | |
| 5325 | Examples |
| 5326 | -------- |
| 5327 | |
| 5328 | Create slices |
| 5329 | |
| 5330 | >>> import dask.array as da |
| 5331 | >>> import numpy as np |
| 5332 | |
| 5333 | >>> data = [da.from_array(np.ones((4, 4)), chunks=(2, 2)) |
| 5334 | ... for i in range(3)] |
| 5335 | |
| 5336 | >>> x = da.stack(data, axis=0) |
| 5337 | >>> x.shape |
| 5338 | (3, 4, 4) |
| 5339 | |
| 5340 | >>> da.stack(data, axis=1).shape |
| 5341 | (4, 3, 4) |
| 5342 | |
| 5343 | >>> da.stack(data, axis=-1).shape |
| 5344 | (4, 4, 3) |
| 5345 | |
| 5346 | Result is a new dask Array |
| 5347 | |
| 5348 | See Also |
| 5349 | -------- |
| 5350 | concatenate |
| 5351 | """ |
| 5352 | from dask.array import wrap |
| 5353 | |
| 5354 | seq = [asarray(a, allow_unknown_chunksizes=allow_unknown_chunksizes) for a in seq] |
| 5355 | |
| 5356 | if not seq: |
| 5357 | raise ValueError("Need array(s) to stack") |
| 5358 | if not allow_unknown_chunksizes and not all(x.shape == seq[0].shape for x in seq): |
| 5359 | idx = first(i for i in enumerate(seq) if i[1].shape != seq[0].shape) |
| 5360 | raise ValueError( |
| 5361 | "Stacked arrays must have the same shape. The first array had shape " |
| 5362 | f"{seq[0].shape}, while array {idx[0] + 1} has shape {idx[1].shape}." |
| 5363 | ) |
| 5364 |