通过指定行和列从另一个数组创建NumPy数组 [英] Create NumPy array from another array by specifying rows and columns
问题描述
如何通过指定要包括哪些行和列(分别由x
和y
指示)来创建NumPy数组B
,它是NumPy数组A
的子数组?
How can I create a NumPy array B
which is a sub-array of a NumPy array A
, by specifying which rows and columns (indicated by x
and y
respectively) are to be included?
例如:
A = numpy.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]])
x = [0, 2]
y = [1, 3, 4]
B = # Do something .....
应提供输出:
>>> B
array([[2, 4, 5], [12, 14, 15]])
推荐答案
The best way to do this is to use the ix_
function: see the answer by MSeifert for details.
或者,您可以通过x
和y
使用链式索引操作:
Alternatively, you could use chain the indexing operations using x
and y
:
>>> A[x][:,y]
array([[ 2, 4, 5],
[12, 14, 15]])
第一个x
用于选择A
的行.接下来,[:,y]
选择由y
的元素指定的子数组的列.
First x
is used to select the rows of A
. Next, [:,y]
picks out the columns of the subarray specified by the elements of y
.
在这种情况下,链接是对称的:如果愿意,还可以先使用A[:,y][x]
选择列.
The chaining is symmetric in this case: you can also choose the columns first with A[:,y][x]
if you wish.
这篇关于通过指定行和列从另一个数组创建NumPy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!