Expand the shape of an array. Insert a new axis that will appear at the `axis` position in the expanded array shape. Parameters ---------- a : array_like Input array. axis : int or tuple of ints Position in the expanded axes where the new axis (or axes)
(a, axis)
| 512 | |
| 513 | @array_function_dispatch(_expand_dims_dispatcher) |
| 514 | def expand_dims(a, axis): |
| 515 | """ |
| 516 | Expand the shape of an array. |
| 517 | |
| 518 | Insert a new axis that will appear at the `axis` position in the expanded |
| 519 | array shape. |
| 520 | |
| 521 | Parameters |
| 522 | ---------- |
| 523 | a : array_like |
| 524 | Input array. |
| 525 | axis : int or tuple of ints |
| 526 | Position in the expanded axes where the new axis (or axes) is placed. |
| 527 | |
| 528 | .. deprecated:: 1.13.0 |
| 529 | Passing an axis where ``axis > a.ndim`` will be treated as |
| 530 | ``axis == a.ndim``, and passing ``axis < -a.ndim - 1`` will |
| 531 | be treated as ``axis == 0``. This behavior is deprecated. |
| 532 | |
| 533 | Returns |
| 534 | ------- |
| 535 | result : ndarray |
| 536 | View of `a` with the number of dimensions increased. |
| 537 | |
| 538 | See Also |
| 539 | -------- |
| 540 | squeeze : The inverse operation, removing singleton dimensions |
| 541 | reshape : Insert, remove, and combine dimensions, and resize existing ones |
| 542 | atleast_1d, atleast_2d, atleast_3d |
| 543 | |
| 544 | Examples |
| 545 | -------- |
| 546 | >>> import numpy as np |
| 547 | >>> x = np.array([1, 2]) |
| 548 | >>> x.shape |
| 549 | (2,) |
| 550 | |
| 551 | The following is equivalent to ``x[np.newaxis, :]`` or ``x[np.newaxis]``: |
| 552 | |
| 553 | >>> y = np.expand_dims(x, axis=0) |
| 554 | >>> y |
| 555 | array([[1, 2]]) |
| 556 | >>> y.shape |
| 557 | (1, 2) |
| 558 | |
| 559 | The following is equivalent to ``x[:, np.newaxis]``: |
| 560 | |
| 561 | >>> y = np.expand_dims(x, axis=1) |
| 562 | >>> y |
| 563 | array([[1], |
| 564 | [2]]) |
| 565 | >>> y.shape |
| 566 | (2, 1) |
| 567 | |
| 568 | ``axis`` may also be a tuple: |
| 569 | |
| 570 | >>> y = np.expand_dims(x, axis=(0, 1)) |
| 571 | >>> y |
searching dependent graphs…