numpy.expand_dims() – The NumPy expand_dims Python Function

Introduction to NumPy expand_dims Python Function

The enlarged dimensions of an array may be obtained by using the numpy.expand_dims() function.


numpy.expand_dims(a, axis)


  • a: array-like [input array]
  • axis: int or tuple of ints
    • Deprecated since version 1.13.0: Passing an axis where axis > a.ndim will be treated as axis == a.ndim, and passing axis < -a.ndim – 1 will be treated as axis == 0. This behavior is deprecate.
    • Changed in version 1.18.0: A tuple of axes is now supported. Out-of-range axes as described above are now forbidden and raise an AxisError.

Return: Return the expanded array.

Code Examples of NumPy expand_dims Function

Example 01: In this example, we can see that by using the numpy.expand_dims() function. We can receive the expanded array.

# welcome to
# import numpy
import numpy as np

# using Numpy.expand_dims() function
softhunt = np.array([1, 2])

softhunt = np.expand_dims(softhunt, axis = 0)


(1, 2)

Example 02:

# welcome to
# import numpy
import numpy as np

# using Numpy.expand_dims() function
softhunt = np.array([[1, 2], [7, 8]])

softhunt = np.expand_dims(softhunt, axis = 1)


(2, 2)
(2, 1, 2)

Note: These programs will not run in online IDEs. Please test them on your systems to see how they operate.


Why do we use NumPy expand_dims?

The expand_dims() function is use to expand the shape of an array.

How do I import a NumPy module?

Following are the steps to import a NumPy module.

  • Step01: Check Python Version. Before you can install NumPy. You need to know which Python version you have.
  • Step02: Install Pip. The easiest way to install NumPy is by using Pip.
  • Step03: Install NumPy.
  • Step04: Verify NumPy Installation.
  • Step05: Import the NumPy Package.

Why is my import NumPy not working?

If Python import NumPy doesn’t work, it’s either because the module isn’t install or because it’s corrupt. Uninstall the corrupted module first, then reinstall it to fix it.


That’s all for this article, if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn. And make sure you check out our NumPy tutorials.

Suggested Articles:

  1. numpy.atleast_1d() – The NumPy atleast_1d Python Function
  2. numpy.atleast_2d() – The NumPy atleast_2d Python Function
  3. numpy.atleast_3d() – The NumPy atleast_3d Python Function
  4. Python NumPy – broadcast_to() and broadcast_arrays()

Leave a Comment