Remove axes of length one from an array over specific axis in Numpy


Squeeze the Array shape using the numpy.squeeze() method. This removes axes of length one from an array over specific axis. The axis is set using the "axis" parameter.

The function returns the input array, but with all or a subset of the dimensions of length 1 removed. This is always a itself or a view into the input array. If all axes are squeezed, the result is a 0d array and not a scalar.

The axis selects a subset of the entries of length one in the shape. If an axis is selected with shape entry greater than one, an error is raised.

Steps

At first, import the required library −

import numpy as np

Creating a numpy array using the array() method. We have added elements of int type −

arr = np.array([[[57, 78], [54, 69]]])

Display the array −

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

Check the Dimensions −

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

Get the Datatype −

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

Display the shape of array −

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

Squeeze the Array shape using the numpy.squeeze() method. The axis is set using the "axis" parameter −

print("
Squeeze the shape of Array...
",np.squeeze(arr, axis = 0).shape)

Example

import numpy as np

# Creating a numpy array using the array() method
# We have added elements of int type
arr = np.array([[[57, 78], [54, 69]]])

# Display the array
print("Our Array...
",arr) # Check the Dimensions print("
Dimensions of our Array...
",arr.ndim) # Get the Datatype print("
Datatype of our Array object...
",arr.dtype) # Display the shape of array print("
Array Shape...
",arr.shape) # Squeeze the Array shape using the numpy.squeeze() method # The axis is set using the "axis" parameter print("
Squeeze the shape of Array...
",np.squeeze(arr, axis = 0).shape)

Output

Our Array...
[[[57 78]
[54 69]]]

Dimensions of our Array...
3

Datatype of our Array object...
int64

Array Shape...
(1, 2, 2)

Squeeze the shape of Array...
(2, 2)

Updated on: 18-Feb-2022

106 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements