numpy.squeeze#
- numpy.squeeze(a, axis=None)[原始碼]#
從 a 中移除長度為一的軸。
- 參數:
- a類陣列
輸入資料。
- axisNone 或 int 或 int 元組,選填
選擇形狀中長度為一的項目的子集。如果選擇的軸的形狀項目大於一,則會引發錯誤。
- 回傳值:
- squeezedndarray
輸入陣列,但已移除所有或部分長度為 1 的維度。這始終是 a 本身或是 a 的視圖。請注意,如果所有軸都被擠壓,則結果是 0 維陣列而不是純量。
- 引發:
- ValueError
如果 axis 不是 None,且要擠壓的軸長度不是 1
另請參閱
expand_dims
反向操作,新增長度為一的項目
reshape
插入、移除和合併維度,以及調整現有維度的大小
範例
>>> import numpy as np >>> x = np.array([[[0], [1], [2]]]) >>> x.shape (1, 3, 1) >>> np.squeeze(x).shape (3,) >>> np.squeeze(x, axis=0).shape (3, 1) >>> np.squeeze(x, axis=1).shape Traceback (most recent call last): ... ValueError: cannot select an axis to squeeze out which has size not equal to one >>> np.squeeze(x, axis=2).shape (1, 3) >>> x = np.array([[1234]]) >>> x.shape (1, 1) >>> np.squeeze(x) array(1234) # 0d array >>> np.squeeze(x).shape () >>> np.squeeze(x)[()] 1234