Numpy - 从数组中切片二维行或列向量 [英] Numpy - slicing 2d row or column vector from array
问题描述
我试图找到一个巧妙的小技巧来从二维数组中切片行/列并获得 (col_size x 1)
或 (1 x row_size)代码>.
有没有比在每次切片后使用 numpy.reshape()
更简单的方法?
干杯,斯蒂芬
您可以在一次操作中切片和插入新轴.例如,这是一个二维数组:
<预><代码>>>>a = np.arange(1, 7).reshape(2, 3)>>>一种数组([[1, 2, 3],[4, 5, 6]])要切出单个列(返回形状为 (2, 1)
的数组),使用 None
作为第三维进行切片:
要切出单个 行(返回形状为 (1, 3)
的数组),使用 None
作为第二个维度进行切片:
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)
.
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]])
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]])
这篇关于Numpy - 从数组中切片二维行或列向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!