[파이썬][numpy] numpy `squeeze` 함수

NumPy, short for Numerical Python, is a powerful library in Python used for working with arrays and numerical computations. One useful function provided by NumPy is the squeeze function. In this blog post, we will explore what the squeeze function does and how it can be used in Python.

What is the squeeze function?

The squeeze function in NumPy is used to remove single-dimensional entries from the shape of an array. It returns the array with all single-dimensional dimensions removed, effectively reducing the rank of the input array by one.

Let’s consider the following example:

import numpy as np

a = np.array([[[1], [2], [3]]])
print("Original array shape:", a.shape)

b = np.squeeze(a)
print("Squeezed array shape:", b.shape)

Output:

Original array shape: (1, 3, 1)
Squeezed array shape: (3,)

In this example, we have a 3-dimensional array a with shape (1, 3, 1). The squeeze function removes the single-dimensional entries and returns a new array b with shape (3,). The array b contains the same elements as a, but without the unnecessary single-dimensional dimensions.

Usage of the squeeze function

The squeeze function can be used in various scenarios, such as:

Removing unnecessary dimensions

When working with arrays that have unnecessary single-dimensional dimensions, the squeeze function can be used to remove them and simplify the shape of the array. This is particularly useful when dealing with data that has been reshaped or expanded.

Reshaping arrays

In certain cases, the squeeze function can be used to reshape an array. By removing the single-dimensional dimensions, the shape of the array can be changed according to specific requirements.

Conclusion

In this blog post, we have explored the squeeze function in NumPy, which allows us to remove single-dimensional entries from the shape of an array. We have seen how the function can be used to simplify the shape of an array and reshape it according to specific requirements. The squeeze function is a handy tool to have in your arsenal when working with arrays in Python.