NumPy 2d 数组的切片,或者如何从 nxn 数组(n>m)中提取 mxm 子矩阵? [英] Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?

查看:31
本文介绍了NumPy 2d 数组的切片,或者如何从 nxn 数组(n>m)中提取 mxm 子矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对一个 NumPy nxn 数组进行切片.我想提取该数组的 m 行和列的任意选择(即行/列数没有任何模式),使其成为一个新的 mxm 数组.在这个例子中,假设数组是 4x4,我想从中提取一个 2x2 的数组.

I want to slice a NumPy nxn array. I want to extract an arbitrary selection of m rows and columns of that array (i.e. without any pattern in the numbers of rows/columns), making it a new, mxm array. For this example let us say the array is 4x4 and I want to extract a 2x2 array from it.

这是我们的数组:

from numpy import *
x = range(16)
x = reshape(x,(4,4))

print x
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]

要删除的行和列相同.最简单的情况是当我想提取位于开头或结尾的 2x2 子矩阵时,即:

The line and columns to remove are the same. The easiest case is when I want to extract a 2x2 submatrix that is at the beginning or at the end, i.e. :

In [33]: x[0:2,0:2]
Out[33]: 
array([[0, 1],
       [4, 5]])

In [34]: x[2:,2:]
Out[34]: 
array([[10, 11],
       [14, 15]])

但是如果我需要删除另一种行/列的混合怎么办?如果我需要删除第一行和第三行/行,从而提取子矩阵 [[5,7],[13,15]] 怎么办?可以有任何行/行组合.我在某处读到我只需要使用行和列的索引数组/列表来索引我的数组,但这似乎不起作用:

But what if I need to remove another mixture of rows/columns? What if I need to remove the first and third lines/rows, thus extracting the submatrix [[5,7],[13,15]]? There can be any composition of rows/lines. I read somewhere that I just need to index my array using arrays/lists of indices for both rows and columns, but that doesn't seem to work:

In [35]: x[[1,3],[1,3]]
Out[35]: array([ 5, 15])

我找到了一种方法,那就是:

I found one way, which is:

    In [61]: x[[1,3]][:,[1,3]]
Out[61]: 
array([[ 5,  7],
       [13, 15]])

这个的第一个问题是它几乎不可读,尽管我可以忍受.如果有人有更好的解决方案,我当然希望听到.

First issue with this is that it is hardly readable, although I can live with that. If someone has a better solution, I'd certainly like to hear it.

另一件事是我在论坛上阅读了使用数组索引数组会强制 NumPy 制作所需数组的副本,因此在处理大型数组时,这可能会成为一个问题.为什么会这样/这个机制是如何工作的?

Other thing is I read on a forum that indexing arrays with arrays forces NumPy to make a copy of the desired array, thus when treating with large arrays this could become a problem. Why is that so / how does this mechanism work?

推荐答案

正如 Sven 提到的,x[[[0],[2]],[1,3]] 将返回0 和 2 行与 1 和 3 列匹配,而 x[[[0,2],[1,3]] 将返回值 x[0,1] 和 x[2,3] 在一个数组中.

As Sven mentioned, x[[[0],[2]],[1,3]] will give back the 0 and 2 rows that match with the 1 and 3 columns while x[[0,2],[1,3]] will return the values x[0,1] and x[2,3] in an array.

我给出的第一个例子有一个有用的函数,numpy.ix_.您可以使用 x[numpy.ix_([0,2],[1,3])] 执行与我的第一个示例相同的操作.这可以使您不必输入所有这些额外的括号.

There is a helpful function for doing the first example I gave, numpy.ix_. You can do the same thing as my first example with x[numpy.ix_([0,2],[1,3])]. This can save you from having to enter in all of those extra brackets.

这篇关于NumPy 2d 数组的切片,或者如何从 nxn 数组(n>m)中提取 mxm 子矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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