使用Numpy的类似MATLAB的数组索引 [英] MATLAB-like array indexing with Numpy
问题描述
在MATLAB和Numpy中,都可以通过数组对数组进行索引.但是,行为是不同的.让我通过一个例子对此进行解释.
In both MATLAB and Numpy, arrays can be indexed by arrays. However, the behavior is different. Let me explain this by an example.
MATLAB:
>> A = rand(5,5)
A =
0.1622 0.6020 0.4505 0.8258 0.1067
0.7943 0.2630 0.0838 0.5383 0.9619
0.3112 0.6541 0.2290 0.9961 0.0046
0.5285 0.6892 0.9133 0.0782 0.7749
0.1656 0.7482 0.1524 0.4427 0.8173
>> A([1,3,5],[1,3,5])
ans =
0.1622 0.4505 0.1067
0.3112 0.2290 0.0046
0.1656 0.1524 0.8173
脾气暴躁:
In [2]: A = arange(25).reshape((5,5))
In [3]: A
Out[3]:
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]])
In [6]: A[[0,2,4], [0,2,4]]
Out[6]: array([ 0, 12, 24])
换句话说:MATLAB选择行和列,Numpy压缩"两个索引数组,并使用元组指向条目.
In words: MATLAB selects rows and columns, Numpy "zips" the two index arrays and uses the tuples to point to entries.
如何通过Numpy获得MATLAB行为?
How can I get the MATLAB behavior with Numpy?
推荐答案
您可以执行以下操作:
A[[0,2,4],:][:,[0,2,4]]
这将提供您想要的类似MATLAB的结果.
which will give the MATLAB-like result you want.
值得一提的是,如果您使用切片来建立索引,则会产生类似MATLAB的结果,而不会受到任何黑客攻击,这是相当不一致的:
It's worth being aware that, rather inconsistently, if you use slices for indexing then you get MATLAB-like results without any such hackery:
>>> A[1:3,1:3]
array([[ 6, 7],
[11,12]])
在numpy中,与MATLAB不同,1:3
不仅是[1,2]
或任何类型的缩写. (在这一点上,我不得不提一句您肯定已经知道的东西,即Python的1:3
有点像[1,2]
,而MATLAB的有点像[1,2,3]
:右侧端点包含在MATLAB中而在Python中不包含在内. )
In numpy, unlike MATLAB, 1:3
is not just an abbreviation for [1,2]
or anything of the kind. (At which point I feel obliged to mention something you surely know already, namely that Python's 1:3
is kinda like [1,2]
whereas MATLAB's is kinda like [1,2,3]
: the right-hand endpoint is included in MATLAB and excluded in Python.)
这篇关于使用Numpy的类似MATLAB的数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!