numpy的 - 从切片二维数组的行或列向量 [英] Numpy - slicing 2d row or column vector from array
问题描述
我试图找到一个整洁的小把戏从二维数组切片行/列,并获得(col_size×1)
或<$ C数组$ C>(1×row_size)。
I'm trying to find a neat little trick for slicing a row/column from a 2d array and obtaining an array of (col_size x 1)
or (1 x row_size)
.
难道还有比使用 numpy.reshape()
每次切片后?
Is there an easier way than to use numpy.reshape()
after every slicing?
干杯,
斯蒂芬
Cheers, Stephan
推荐答案
您可以切片,并在一次操作中插入一个新的轴心。例如,这里有一个二维数组:
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]])
要切出一个单一的列的(形状的返回数组(2,1)
),切片与无
作为第三维:
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]])
要切出一个单一的行的(返回形状(1阵列,3)
),切片与无
作为第二个维度:
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]])
这篇关于numpy的 - 从切片二维数组的行或列向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!