Home > Software engineering >  Extract an array of numbers from a Python array
Extract an array of numbers from a Python array

Time:11-21

Suppose I have a 10x10 Python array, M. I would like to extract the 3x3 array with the values of the rows [2,3,5], and columns [2,3,5]. How do I do this? I would like to obtain the equivalent of M[0:3,0:3] but using coordinates [2,3,5] instead of [0,1,2].

I have tried M[[2,3,5],[2,3,5]], but this produces three values, not a 3x3 array.

CodePudding user response:

You could .take() twice

>>> a = np.arange(100).reshape(10,10)
>>> a
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, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
       [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
       [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
       [70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
       [80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
       [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])
>>> np.take(np.take(a, [2,3,5], axis=1), [2,3,5], axis=0)
array([[22, 23, 25],
       [32, 33, 35],
       [52, 53, 55]])

CodePudding user response:

One option to use is numpy.ix_.

It should be as simple as M[np.ix_([2, 3, 5], [2, 3, 5])].

  • Related