Other form to Index in Python

Viewed 98

I am following a Machine Learning course, and in a review of numpy library, a method of indexing is used that I have never seen before. We defined a = np.array([[1,2],[3,4],[5,6]]). Two new arrays are subsequently created: np.array([a[0,0], a[1,1], a[2,1]]. This is the way of indexing that I know. The way of indexing that I don't know is this: print(a[[0,1,2],[0,1,1]]). Could someone help me with an explanation about this latest form of indexing?

2 Answers

When n arrays are passed, where n is the number of array dimensions, they are used as indexes for corresponding dimensions. a[[0,1,2],[0,1,1]] is equivalent to [a[0,0], a[1,1], a[2,1]]

Let me quote numpy docs:

... From each row, a specific element should be selected. The row index is just [0, 1, 2] and the column index specifies the element to choose for the corresponding row, here [0, 1, 0]. Using both together the task can be solved using advanced indexing:

x = np.array([[1, 2], [3, 4], [5, 6]])

x[[0, 1, 2], [0, 1, 0]]
array([1, 4, 5])

It calls integer array indexing. In your example, you are accesing to [[0,1,2],[0,1,1]] indexes of a 1x3 array, called a. It means, you are getting from a:

[
    the first element of the first array,contained in this 1x3 array,
    the second element of the second array, contained in this big array,
    the second element of the third array, contained in the same array
]

Printing out, you will get the output of [1 4 6], because those are the elements in the specified positions ((0,0),(1,1),(2,1)). You can visualize it like a columns and rows scheme:

[[rows],[colums]] # vertically speaking

You select the rows of the items you want in the first sub-array, and the columns in the second one.

Related