numpy.ma.expand_dims#

ma.expand_dims(a, axis)[source]#

扩展数组的形状。

插入一个新轴,该轴将出现在扩展数组形状的 axis 位置。

参数:
aarray_like

输入数组。

axisint 或 tuple of ints

在扩展轴中放置新轴(或多个轴)的位置。

自 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