通过指定行和列从另一个数组创建NumPy数组 [英] Create NumPy array from another array by specifying rows and columns

查看:67
本文介绍了通过指定行和列从另一个数组创建NumPy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过指定要包括哪些行和列(分别由xy指示)来创建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]])

推荐答案

做到这一点的最佳方法是使用ix_函数:请参见

The best way to do this is to use the ix_ function: see the answer by MSeifert for details.

或者,您可以通过xy使用链式索引操作:

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屋!

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