I am not able to understand integer array indexing in numpy.
>>> x = np.array([[1, 2], [3, 4], [5, 6]])
>>> x[[0, 1, 2], [0, 1, 0]]
array([1, 4, 5])
Please explain me what is happening in this?
I am not able to understand integer array indexing in numpy.
>>> x = np.array([[1, 2], [3, 4], [5, 6]])
>>> x[[0, 1, 2], [0, 1, 0]]
array([1, 4, 5])
Please explain me what is happening in this?
In [76]: x = np.array([[1, 2], [3, 4], [5, 6]])
In [77]: x
Out[77]:
array([[1, 2],
[3, 4],
[5, 6]])
Because the 1st and 2nd indexing lists match in size, their values are paired up to select elements from x. I'll illustrate it with list indexing:
In [78]: x[[0, 1, 2], [0, 1, 0]]
Out[78]: array([1, 4, 5])
In [79]: list(zip([0, 1, 2], [0, 1, 0]))
Out[79]: [(0, 0), (1, 1), (2, 0)]
In [80]: [x[i,j] for i,j in zip([0, 1, 2], [0, 1, 0])]
Out[80]: [1, 4, 5]
Or more explicitly, it is returning x[0,0], x[1,1] and x[2,0], as a 1d array. Another way to think it is that you've picked the [0,1,0] elements from the 3 rows (respectively).
I find it easiest to understand as follows:
In [179]: x = np.array([[1, 2], [3, 4], [5, 6]])
In [180]: x
Out[180]:
array([[1, 2],
[3, 4],
[5, 6]])
Say we want to select 1, 4, and 5 from this matrix. So the 0th column of row 0, the 1st column of the 1st row, and the 0th column of the 2nd row. Now provide the index with two arrays (one for each dimension of the matrix), where we populate these arrays with the rows and then the columns we are interested in:
In [181]: rows = np.array([0, 1, 2])
In [182]: cols = np.array([0, 1, 0])
In [183]: x[rows, cols]
Out[183]: array([1, 4, 5])