Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of python code snippet >>numpy.nonzero(row == max(row))[0][0]<< from a script using numpy

Tags:

python

numpy

What does this peace of python code

row = R[i,]
j = numpy.nonzero(row == max(row))[0][0]

do, assuming this output:

command   # output of python
----------------------------------
R.shape   # (224, 24)
type(R)   # <type 'numpy.ndarray'>
type(row) # <type 'numpy.ndarray'>
type(j)   # <type 'numpy.int64'>

(I'll provide more information if required, to answer my question.)

Update:

Sorry, I used two times the variable i. I changed that in the question!

like image 695
Aufwind Avatar asked Dec 28 '22 20:12

Aufwind


2 Answers

The two lines appear to be a roundabout way of saying j = np.argmax(R[i]), i.e. find the column index of the largest element in the i-th row of R, and store the result in j.

like image 74
NPE Avatar answered Dec 30 '22 10:12

NPE


Perhaps an example will help:

In []: R= arange(12).reshape(4, 3)
In []: R
Out[]: 
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])
In []: i= 1
In []: row= R[i, ]
In []: row
Out[]: array([3, 4, 5])
In []: j= nonzero(row== max(row))[0][0]
In []: j
Out[]: 2

Thus the j is the index of the maximum element in the ith row of R. So

In []: R[i, j]
Out[]: 5
like image 34
eat Avatar answered Dec 30 '22 08:12

eat