Unlock the Power of Numpy’s Squeeze Method
When working with arrays in Numpy, it’s not uncommon to encounter singleton dimensions – dimensions with a size of 1. These can make your arrays cumbersome and difficult to work with. That’s where the squeeze method comes in – a powerful tool that removes these singleton dimensions, simplifying your arrays and making them more efficient.
What is the Squeeze Method?
The squeeze method is a Numpy function that eliminates singleton dimensions from an array, returning a new array with the reduced dimensions.
Syntax and Arguments
The syntax of the squeeze method is straightforward: squeeze(array, axis=None)
. The method takes two arguments: array
, the array to be squeezed, and axis
, an optional argument that specifies the axis along which the array is squeezed. If axis
is not provided, it defaults to <code,none< code=””>, and all singleton dimensions are removed.</code,none<>
Examples in Action
Let’s take a look at some examples to see the squeeze method in action.
Example 1: Squeezing a Single-Dimensional Entry
import numpy as np
array1 = np.array([[[1, 2, 3]], [[4, 5, 6]]])
squeezed_array1 = np.squeeze(array1)
print(squeezed_array1) # Output: [[1, 2, 3], [4, 5, 6]]
In this example, we have a 3D array with a single-dimensional entry. When we apply the squeeze method, the singleton dimension is removed, leaving us with a 2D array.
Example 2: Squeezing Multiple Single-Dimensional Entries
import numpy as np
array2 = np.array([[[[1, 2]], [[3, 4]]]])
squeezed_array2 = np.squeeze(array2)
print(squeezed_array2) # Output: [[1, 2], [3, 4]]
What if our array has multiple single-dimensional entries? The squeeze method can handle this too. In this example, we have a 4D array with multiple singleton dimensions. When we apply the squeeze method, all singleton dimensions are removed, leaving us with a 2D array.
Example 3: Squeezing Along a Specific Axis
import numpy as np
array3 = np.array([[[1, 2, 3]], [[4, 5, 6]]])
squeezed_array3 = np.squeeze(array3, axis=1)
print(squeezed_array3) # Output: [[1, 2, 3], [4, 5, 6]]
But what if we want to squeeze our array along a specific axis? We can do this by providing the axis
argument. In this example, we squeeze our array along axis 1, removing the singleton dimension.
Example 4: Squeezing with All Dimensions of Length 1
import numpy as np
array4 = np.array([[[[123]]]])
squeezed_array4 = np.squeeze(array4)
print(squeezed_array4) # Output: 123
print(type(squeezed_array4)) # Output: <class 'numpy.ndarray'>
What happens if all dimensions of our array are of length 1? In this case, the squeeze method returns a scalar value. Note that although 123 is a scalar value, it’s still considered an array.
By mastering the squeeze method, you can simplify your arrays, improve performance, and take your Numpy skills to the next level.