numpy.expand_dims#

numpy.expand_dims(a, axis)[原始碼]#

擴展陣列的形狀。

在擴展陣列形狀中的 axis 位置插入新的軸。

參數:
aarray_like

輸入陣列。

axisint 或 int 元組

新軸(或多個軸)放置在擴展軸中的位置。

版本 1.13.0 開始棄用: 傳遞 axis > a.ndim 的軸將被視為 axis == a.ndim,而傳遞 axis < -a.ndim - 1 將被視為 axis == 0。此行為已被棄用。

返回:
resultndarray

維度增加的 a 檢視。

參見

squeeze

反向操作,移除單例維度

reshape

插入、移除和組合維度,以及調整現有維度的大小

atleast_1d, atleast_2d, atleast_3d

範例

>>> import numpy as np
>>> x = np.array([1, 2])
>>> x.shape
(2,)

以下等效於 x[np.newaxis, :]x[np.newaxis]

>>> y = np.expand_dims(x, axis=0)
>>> y
array([[1, 2]])
>>> y.shape
(1, 2)

以下等效於 x[:, np.newaxis]

>>> y = np.expand_dims(x, axis=1)
>>> y
array([[1],
       [2]])
>>> y.shape
(2, 1)

axis 也可以是元組

>>> y = np.expand_dims(x, axis=(0, 1))
>>> y
array([[[1, 2]]])
>>> y = np.expand_dims(x, axis=(2, 0))
>>> y
array([[[1],
        [2]]])

請注意,某些範例可能會使用 None 而不是 np.newaxis。這些是相同的物件

>>> np.newaxis is None
True