numpy.squeeze#
- numpy.squeeze(a, axis=None)[源]#
从 a 中移除长度为一的轴。
- 参数:
- aarray_like
输入数据。
- axisNone 或 int 或 ints 元组,可选
选择形状中长度为一的条目的一个子集。如果所选轴的形状条目大于一,则会引发错误。
- 返回:
- 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