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

NumpyServer Side ProgrammingProgramming

#### Python Data Science basics with Numpy, Pandas and Matplotlib

Most Popular

63 Lectures 6 hours

#### Data Analysis using NumPy and Pandas

19 Lectures 8 hours

#### Numpy with Python

Most Popular

12 Lectures 3 hours

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. We will set axis 0 here. 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...\n",arr)

Display the shape of array −

print("\nArray Shape...\n",arr.shape)


Check the Dimensions −

print("\nDimensions of our Array...\n",arr.ndim)

Get the Datatype −

print("\nDatatype of our Array object...\n",arr.dtype)

Get the number of elements in an array −

print("\nSize of array...\n",arr.size)

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

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


Display the expanded array −

print("\nResultant expanded array....\n", res)

Display the shape of the expanded array −

print("\nShape of the expanded array...\n",res.shape)

Check the Dimensions

print("\nDimensions of our Array...\n",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...\n",arr)

# Display the shape of array
print("\nArray Shape...\n",arr.shape)

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

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

# Get the number of elements in an array
print("\nSize of array...\n",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)

# Display the expanded array
print("\nResultant expanded array....\n", res)

# Display the shape of the expanded array
print("\nShape of the expanded array...\n",res.shape)

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

## Output

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

Array Shape...
(6,)

Dimensions of our Array...
1

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, 6)

Dimensions of our Array...
2