You can slice and insert a new axis in one single operation. For example, here's a 2D array:
>>> a = np.arange(1, 7).reshape(2, 3)
>>> a
array([[1, 2, 3],
[4, 5, 6]])
To slice out a single column (returning array of shape (2, 1)
), slice with None
as the third dimension:
>>> a[:, 1, None]
array([[2],
[5]])
To slice out a single row (returning array of shape (1, 3)
), slice with None
as the second dimension:
>>> a[0, None, :]
array([[1, 2, 3]])
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…