0

# Why this output?

Hi guys, I'have started Numpy and I have to admit I pretty hate its "syntax". Here my problem: import numpy as np a= np.arange(12).reshape(3,4) print(a) i= np.array([[0,1],[1,2]]) j= np.array([[2,1],[3,3]]) print(a[i,j]) OUTPUT= array([[ 2, 5], [ 7, 11]]) Why?????? I don't understand how it is referring to indexes and dimensions! why these numbers as output? Seriously I'm getting crazy...

22nd Jul 2019, 1:38 PM
polargnome
+ 1
"The resultant array has the same shape as the index arrays, and the values correspond to the index set for each position in the index arrays". This means the printed values correspond to a[0,2] == 2, a[1,1] == 5, a[1,3] == 7, a[2,3] == 11. https://docs.scipy.org/doc/numpy/user/basics.indexing.html#indexing-multi-dimensional-arrays
22nd Jul 2019, 2:28 PM
Diego
+ 1
You're right: a[0,1] == 1. The thins is your code prints a[0,2] == 2. The problem is the indexes of the resultant array aren't [0,1], [1,2], [2,1], [3,3]. To get the correct ones take each index from array "i" and pair it with the corresponding index of array "j" as follows: 1. The first element of "i" (0) goes with the first element of "j" (2) resulting in [0,2]. 2. The second element of "i" (1) goes with the second element of "j" (1) resulting in [1,1]. At the end you get [0,2], [1,1], [1,3], [2,3].
22nd Jul 2019, 3:10 PM
Diego
0
Ok, so far I understand that it's indexing the element in 2 rows and two columns. The point is why THOSE numbers? I mean, I thought that a[0,1] was supposed to be nrow=0 and ncol=1. So, in a= arange(12).reshape(3,4) is: a = [0,1,2,3, 4,5,6,7, 8,9,10,11] First element [0,1] Line 0, element 1 = 1. Why 2? Second element [1,2] Line 1,element 2 = 6. Why 5? Third element [2,1] """""""""""""""""""""""""""""""" Fourth element [3,3] """"""""""""""""""""""""""""""""" It's clear I didn't understand how to proceed in this indexing
22nd Jul 2019, 2:58 PM
polargnome
0
Ok perfect, I got it now!! I only have one doubt left: why do I have to "joining" the couples as columns ([0,2],[1,1],[1,3],[2,3])? Anyway THANKS MATE!
22nd Jul 2019, 3:37 PM
polargnome