# Expand the shape of an array over tuple of axis in Numpy

To expand the shape of an array, use the numpy.expand_dims() method. Insert a new axis that will appear at the axis position in the expanded array shape. The function returns the View of the input array with the number of dimensions increased.

NumPy offers comprehensive mathematical functions, random number generators, linear algebra routines, Fourier transforms, and more. It supports a wide range of hardware and computing platforms, and plays well with distributed, GPU, and sparse array libraries.

## Steps

At first, import the required library −

import numpy as np

Creating an array using the array() method −

arr = np.array([[5, 10, 15], [20, 25, 30]])


Display the array −

print("Our Array...",arr)

Display the shape of array −

print("Array Shape...",arr.shape)


Check the Dimensions −

print("Dimensions of our Array...",arr.ndim)

Get the Datatype −

print("Datatype of our Array object...",arr.dtype)


Get the number of elements in an array −

print("Size of array...",arr.size)

To expand the shape of an array, use the numpy.expand_dims() method −

res = np.expand_dims(arr, axis=(0, 1))


Display the expanded array −

print("Resultant expanded array....", res)

Display the shape of the expanded array −

print("Shape of the expanded array...",res.shape)


Check the Dimensions −

print("Dimensions of our Array...",res.ndim)

## Example

import numpy as np

# Creating an array using the array() method
arr = np.array([[5, 10, 15], [20, 25, 30]])

# Display the array
print("Our Array...",arr)

# Display the shape of array
print("Array Shape...",arr.shape)

# Check the Dimensions
print("Dimensions of our Array...",arr.ndim)

# Get the Datatype
print("Datatype of our Array object...",arr.dtype)

# Get the number of elements in an array
print("Size of array...",arr.size)

# To expand the shape of an array, use the numpy.expand_dims() method
# Insert a new axis that will appear at the axis position in the expanded array shape.
res = np.expand_dims(arr, axis=(0, 1))

# Display the expanded array
print("Resultant expanded array....", res)

# Display the shape of the expanded array
print("Shape of the expanded array...",res.shape)

# Check the Dimensions
print("Dimensions of our Array...",res.ndim)

## Output

Our Array...
[[ 5 10 15]
[20 25 30]]

Array Shape...
(2, 3)

Dimensions of our Array...
2

Datatype of our Array object...
int64

Size of array...
6

Resultant expanded array....
[[[[ 5 10 15]
[20 25 30]]]]

Shape of the expanded array...
(1, 1, 2, 3)

Dimensions of our Array...
4