NumPy squeeze() 函式



Numpy 的squeeze()函式用於從陣列的形狀中刪除一維條目。

此函式用於消除大小為 1 的維度,這可以簡化陣列操作。例如,如果我們有一個形狀為 (1, 3, 1, 5) 的陣列,透過應用squeeze() 將將其轉換為形狀為 (3, 5) 的陣列,方法是刪除單例維度。

此函式採用可選的axis引數來指定要刪除的維度,但如果未提供,則會刪除所有單例維度。

結果是一個具有較少維度但資料相同的新陣列。

語法

Numpy squeeze()函式的語法如下:

numpy.squeeze(a, axis=None)

引數

以下是 Numpy squeeze()函式的引數:

  • a(array_like): 這是輸入資料,應為陣列或類陣列物件。
  • axis(None 或 int 或 int 元組,可選): 此引數選擇形狀中單維條目的子集。如果指定了軸,則只會壓縮該軸或這些軸。如果未指定軸,則會刪除所有單維條目。如果指定的軸的大小不為 1,則會引發錯誤。

返回值

此函式返回輸入陣列,但刪除了所有或一部分大小為 1 的維度。這不會修改原始陣列,而是返回一個新陣列。

示例 2

以下是使用 Numpy squeeze()函式的示例。在此示例中,形狀為 (1, 3, 1) 的陣列 'a' 被壓縮以刪除所有單維條目,從而得到形狀為 (3,) 的陣列:

import numpy as np

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

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

輸出

Original array shape: (1, 3, 1)
Squeezed array shape: (3,)
Squeezed array: [1 2 3]

示例 2

在此示例中,我們嘗試壓縮一個非單維軸,即軸 1,這會導致 ValueError,因為軸 1 的大小為 3:

import numpy as np

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

try:
    # Attempting to squeeze a non-single-dimensional axis
    squeezed_a = np.squeeze(a, axis=1)
except ValueError as e:
    print("Error:", e)

輸出

Original array shape: (1, 3, 1)
Error: cannot select an axis to squeeze out which has size not equal to one

示例 3

以下示例展示瞭如何使用numpy.squeeze()從陣列的形狀中刪除一維條目:

import numpy as np

# Creating a 3D array with shape (1, 3, 3)
x = np.arange(9).reshape(1, 3, 3)

print('Array X:')
print(x)
print('\n')

# Removing single-dimensional entries from the shape of x
y = np.squeeze(x)

print('Array Y:')
print(y)
print('\n')

# Printing the shapes of the arrays
print('The shapes of X and Y array:')
print(x.shape, y.shape)

輸出

Array X:
[[[0 1 2]
  [3 4 5]
  [6 7 8]]]


Array Y:
[[0 1 2]
 [3 4 5]
 [6 7 8]]


The shapes of X and Y array:
(1, 3, 3) (3, 3)
numpy_array_manipulation.htm
廣告