Expand the shape of an array over axis 1 in Numpy

NumpyServer Side ProgrammingProgramming

To expand the shape of an array, use the numpy.expand_dims() method. Insert a new array 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...\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=1)

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=1)

# 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...
(6, 1)

Dimensions of our Array...
2
raja
Updated on 17-Feb-2022 09:13:09

Advertisements