Skip to content
Advertisement

What does numpy.ix_() function do and what is the output used for?

Below shows the output from numpy.ix_() function. What is the use of the output? It’s structure is quite unique.

import numpy as np

>>> gfg = np.ix_([1, 2, 3, 4, 5, 6], [11, 12, 13, 14, 15, 16], [21, 22, 23, 24, 25, 26], [31, 32, 33, 34, 35, 36] )
>>> gfg
(array([[[[1]]],
        [[[2]]],
        [[[3]]],
        [[[4]]],
        [[[5]]],
        [[[6]]]]), 
 
 array([[[[11]],
         [[12]],
         [[13]],
         [[14]],
         [[15]],
         [[16]]]]), 
 
 array([[[[21],
          [22],
          [23],
          [24],
          [25],
          [26]]]]), 
 
 array([[[[31, 32, 33, 34, 35, 36]]]]))

Advertisement

Answer

According to numpy doc:

Construct an open mesh from multiple sequences. 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. Using ix_ one can quickly construct index arrays that will index the cross product. a[np.ix_([1,3],[2,5])] returns the array [[a[1,2] a[1,5]], [a[3,2] a[3,5]]].

numpy.ix_()‘s main use is to create an open mesh so that we can use it to select specific indices from an array (specific sub-array). An easy example to understand it is:

Say you have a 2D array of shape (5,5), and you would like to select a sub-array that is constructed by selecting the rows 1 and 3 and columns 0 and 3. You can use np.ix_ to create a (index) mesh so as to be able to select the sub-array as follows in the example below:

a = np.arange(5*5).reshape(5,5)
[[ 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]]

sub_indices = np.ix_([1,3],[0,3])
(array([[1],
       [3]]), array([[0, 3]]))

a[sub_indices]
[[ 5  8]
 [15 18]]

which is basically the selected sub-array from a that is in rows array([[1],[3]]) and columns array([[0, 3]]):

 col 0    col 3
   |        |
   v        v
[[ 0  1  2  3  4]   
 [ 5  6  7  8  9]   <- row 1
 [10 11 12 13 14]
 [15 16 17 18 19]   <- row 3
 [20 21 22 23 24]]

Please note in the output of the np.ix_, the N-arrays returned for the N 1-D input indices you feed to np.ix_ are returned in a way that first one is for rows, second one is for columns, third one is for depth and so on. That is why in the above example, array([[1],[3]]) is for rows and array([[0, 3]]) is for columns. Same goes for the example OP provided in the question. The reason behind it is the way numpy uses advanced indexing for multi-dimensional arrays.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement