0

say I have a numpy list of lists:

import numpy as np
ab=np.array([[1,2,3,4,5],[2,3,4,5,6],[3,4,5,3,6]])

Now say I want to have the submatrix the first two rows and column 1 and 3, I would do

print(ab[0:2,[1,3]])

Now if I want row 0 and 2 and columns 1 and 3, I would try:

print(ab[np.array([0,2]),np.array([1,3])])

But then I get :

[3 6]

This is entries wise seeking and not rows and columns wise submatrixing.

How do you do it?

user42493
  • 813
  • 4
  • 14
  • 34
  • In a situation where you are selecting rows/columns with static steps, you can do something like this, `print(ab[0:3:2, 1:4:2])` – ywbaek Apr 25 '20 at 21:56

1 Answers1

1

When you select sub-arrays with two broadcastable indices arrays, like array[arr_1, arr2], it will match each element of arr_1 to arr_2 and select corresponding element of array. If you wish to select all rows in arr_1 and all columns in arr_2, the most elegant way would be using np.ix_. The code would be:

ab[np.ix_(np.array([0,2]),np.array([1,3]))]

output:

[[2 4]
 [4 3]]

About np.ix_: From numpy doc: This function takes N 1-D sequences and returns N outputs with N dimensions each, such that the shape is 1 in all but one dimension and the dimension with the non-unit shape value cycles through all N dimensions.

Which means you can extend this to ANY dimension array. For array of N dimensions, calling np.ix_(arr_1, arr_2, ..., arr_N) will create N indices array, each will cycle through all arr_i rows of dimension i in array.

Ehsan
  • 12,072
  • 2
  • 20
  • 33