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.

JavaScript

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:

JavaScript

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

JavaScript

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