切片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)?
问题描述
我想对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]]
将返回与1和3列匹配的0和2行,而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屋!