Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create NumPy array from another array by specifying rows and columns

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?

For example:

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 .....

Should give the output:

>>> B
array([[2, 4, 5], [12, 14, 15]])
like image 667
Karnivaurus Avatar asked Mar 19 '23 03:03

Karnivaurus


1 Answers

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

Alternatively, you could use chain the indexing operations using x and y:

>>> A[x][:,y]
array([[ 2,  4,  5],
       [12, 14, 15]])

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.

The chaining is symmetric in this case: you can also choose the columns first with A[:,y][x] if you wish.

like image 95
Alex Riley Avatar answered Mar 26 '23 01:03

Alex Riley