Reputation: 2617
Consider the following picture of my numpy matrix in Python 3.5. A is a matrix with shape (35,50).
The line containing np.max(A)
returns the right value of the max, the max is indeed 2372 in my dataset. However When I tried to reproduce the numpy documentation as seen here:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.argmax.html
I didn't get results that resembled the results in the documentation. All the index pairs are different. I tried the first index pair: A[18][29]
but it was the index of an element with value 506, when I thought this would only return indices for the max of the matrix. That leaves me with 2 questions:
If these index pairs aren't indices of the max of the matrix, i.e. np.max(A)
, then what are they?
Does numpy have a means to return the index of the actual element within a matrix, of any given shape (my shape is 35,50)? Ideally, if I input: A[row_index][column_index]
I would like the output to be a scalar element of value equal to np.max(A)
, in my case that value would be 2372.
I'm not exactly sure why it's not working the way I'd expect it to, if I had to guess, I'd say it has something to do with arrays within arrays, or I'm just not using the right numpy extension.
Please advise,
Thank you
Upvotes: 1
Views: 1765
Reputation: 231395
row_index
is the index of the maximum for each column, 50 columns, 50 indices.
col_index
is the index of the maximum for each rows, 35 values.
It doesn't make sense to pair up values in those two arrays. Yes, one of those pairs will be the index of the whole-array max, but you can't tell just by looking them.
========================
In [573]: x
Out[573]:
array([[15, 8, 6, 3, 4, 5],
[22, 1, 13, 10, 18, 7],
[21, 14, 20, 16, 9, 2],
[11, 12, 23, 19, 17, 0]])
In [574]: i0=np.argmax(x,axis=0)
In [575]: i1=np.argmax(x,axis=1)
In [576]: i0
Out[576]: array([1, 2, 3, 3, 1, 1], dtype=int32)
In [577]: i1
Out[577]: array([0, 0, 0, 2], dtype=int32)
To fetch the max values, we have to combine these indices with the correct shape of np.arange
.
In [578]: x[i0,np.arange(6)]
Out[578]: array([22, 14, 23, 19, 18, 7])
In [579]: x[np.arange(4),i1]
Out[579]: array([15, 22, 21, 23])
23
is present in both, but not at the same index
In [580]: np.argmax(x)
Out[580]: 20 # location in the flattened version of x
In [581]: x.flat[20]
Out[581]: 23
In [582]: x[i0[2], i1[3]] # (3, 2)
Out[582]: 23
To convert the flat index to 2d, use:
In [583]: np.unravel_index(20,x.shape)
Out[583]: (3, 2)
In [584]: x[3,2]
Out[584]: 23
Upvotes: 1