从2D Numpy数组中提取多组行/列
我有一个2D Numpy数组,我想从中提取多组行/列。
# img is 2D array
img = np.arange(25).reshape(5,5)
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
我知道要提取一组行/列的语法。如下所示,以下将提取前4行和第三列和第4列,
img[0:4, 2:4]
array([[ 2, 3],
[ 7, 8],
[12, 13],
[17, 18]])
但是,如果我想提取多组行和/或列,该语法是什么?我尝试了以下操作,但它导致Invalid语法错误
img[[0,2:4],2]
我从上面命令中寻找的输出是
array([[ 2],
[12],
[17]])
我尝试搜索的,但是它仅导致一组行/列或提取我知道该怎么做的离散行/列,例如使用np.ix。
对于上下文,我实际上要处理的2D数组的尺寸〜800x1200,从这个数组中,我想一次提取多个行和列范围。因此,类似img [[0:100,120:210:210,400,500:600],[1:450,500:5550,600,700:950]]
。
I have a 2D numpy array from which I want to extract multiple sets of rows/ columns.
# img is 2D array
img = np.arange(25).reshape(5,5)
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
I know the syntax to extract one set of row/ column. The following will extract the first 4 rows and the 3rd and 4th column as shown below
img[0:4, 2:4]
array([[ 2, 3],
[ 7, 8],
[12, 13],
[17, 18]])
However, what is the syntax if I want to extract multiple sets of rows and/or columns? I tried the following but it leads to an invalid syntax
error
img[[0,2:4],2]
The output that I am looking for from the above command is
array([[ 2],
[12],
[17]])
I tried searching for this but it only leads to results for one set of rows/ columns or extracting discrete rows/ columns which I know how to do, like using np.ix.
For context, the 2D array that I am actually dealing with has the dimensions ~800X1200, and from this array I want to extract multiple ranges of rows and columns in one go. So something like img[[0:100, 120:210, 400, 500:600], [1:450, 500:550, 600, 700:950]]
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
iiuc,您可以使用 /a>从切片中生成索引:
输出:
中间体:
IIUC, you can use
numpy.r_
to generate the indices from the slice:output:
intermediates:
您可以使用
numpy.r _
创建切片:然后,您可以获取特定的行和列,如下所示:
You can create your slices with
numpy.r_
:Then you can get the specific rows and columns as follows: