I am learning numpy framework.This piece of code I don't understand.
import numpy as np
a =np.array([[0,1,2],[3,4,5],[6,7,8],[9,10,11]])
print(a)
row = np.array([[0,0],[3,3]])
col = np.array([[0,2],[0,2]])
b = a[row,col]
print("This is b array:",b)
This b array returns the corner values of a array, that is, b equals [[0,2],[9,11]].
You're indexing
ausing two equally shaped2d-arrays, hence you're output array will also have the same shape ascolandrow. To better understand howarray indexingworks you can check the docs, where as shown, indexing with1d-arraysover the existing axis' of a given array works as follows:Where the same logic applies in the case of indexing with
2d-arraysover each axis, but instead you'd have aresultarray with up toi_N_Mindices.So going back to your example you are essentially selecting from the rows of
abased onrow, and from thoserowsyou are selecting some columnscol. You might find it more intuitive to translate the row and column indices into(x,y)coordinates:Which, by accordingly selecting from
a, results in the output array: