Numpy - 从数组中切片二维行或列向量 [英] Numpy - slicing 2d row or column vector from array

查看:44
本文介绍了Numpy - 从数组中切片二维行或列向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一个巧妙的小技巧来从二维数组中切片行/列并获得 (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 作为第三维进行切片:

<预><代码>>>>a[:, 1, 无]数组([[2],[5]])

要切出单个 (返回形状为 (1, 3) 的数组),使用 None 作为第二个维度进行切片:

<预><代码>>>>[0, 无, :]数组([[1, 2, 3]])

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆