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)
| 5505 | |
| 5506 | |
| 5507 | def stack(seq, axis=0, allow_unknown_chunksizes=False): |
| 5508 | """ |
| 5509 | Stack arrays along a new axis |
| 5510 | |
| 5511 | Given a sequence of dask arrays, form a new dask array by stacking them |
| 5512 | along a new dimension (axis=0 by default) |
| 5513 | |
| 5514 | Parameters |
| 5515 | ---------- |
| 5516 | seq: list of dask.arrays |
| 5517 | axis: int |
| 5518 | Dimension along which to align all of the arrays |
| 5519 | allow_unknown_chunksizes: bool |
| 5520 | Allow unknown chunksizes, such as come from converting from dask |
| 5521 | dataframes. Dask.array is unable to verify that chunks line up. If |
| 5522 | data comes from differently aligned sources then this can cause |
| 5523 | unexpected results. |
| 5524 | |
| 5525 | Examples |
| 5526 | -------- |
| 5527 | |
| 5528 | Create slices |
| 5529 | |
| 5530 | >>> import dask.array as da |
| 5531 | >>> import numpy as np |
| 5532 | |
| 5533 | >>> data = [da.from_array(np.ones((4, 4)), chunks=(2, 2)) |
| 5534 | ... for i in range(3)] |
| 5535 | |
| 5536 | >>> x = da.stack(data, axis=0) |
| 5537 | >>> x.shape |
| 5538 | (3, 4, 4) |
| 5539 | |
| 5540 | >>> da.stack(data, axis=1).shape |
| 5541 | (4, 3, 4) |
| 5542 | |
| 5543 | >>> da.stack(data, axis=-1).shape |
| 5544 | (4, 4, 3) |
| 5545 | |
| 5546 | Result is a new dask Array |
| 5547 | |
| 5548 | See Also |
| 5549 | -------- |
| 5550 | concatenate |
| 5551 | """ |
| 5552 | from dask.array import wrap |
| 5553 | |
| 5554 | seq = [asarray(a, allow_unknown_chunksizes=allow_unknown_chunksizes) for a in seq] |
| 5555 | |
| 5556 | if not seq: |
| 5557 | raise ValueError("Need array(s) to stack") |
| 5558 | if not allow_unknown_chunksizes and not all(x.shape == seq[0].shape for x in seq): |
| 5559 | idx = first(i for i in enumerate(seq) if i[1].shape != seq[0].shape) |
| 5560 | raise ValueError( |
| 5561 | "Stacked arrays must have the same shape. The first array had shape " |
| 5562 | f"{seq[0].shape}, while array {idx[0] + 1} has shape {idx[1].shape}." |
| 5563 | ) |
| 5564 |