简体   繁体   中英

np.where to compute age group index

There is a part of the following code that I don't quite understand.

Here is the code:

import numpy as np

medalNames = np.array(['none', 'bronze', 'silver', 'gold'])

ageGroupCategories = np.array(['B','P','G','T'])

allLowerThresholds = np.array([[-1,0,5,10], [0,5,10,15], [0,11,14,17], [0,15,17,19]])

ageGroupIndex = np.where(ageGroup[0] == ageGroupCategories)[0][0]

In the last line, what does the [0][0] do, why doesn't the code work without it?

A few things:

  1. Use embedded Code boxes
  2. Your code isn't working at all because the variable ageGroup doesn't exist

Now to your question:

since it is an array the [0][0] calls on the first row and first column of the result of the array np.where() .

Your question is general and related to the numpy.where function.

Let's take a simple example as follows:

A=np.array([[3,2,1],[4,5,1]])
# array([[3, 2, 1],
#        [4, 5, 1]])

print(np.where(A==1))
# (array([0, 1]), array([2, 2]))

As you can see the np.where function returns a tuple. The first element (it's a numpy array) of the tuple is the row/line index, and the second element (it's again a numpy array), is the column index.

np.where(A==1)[0] # this is the first element of the tuple thus, 
                  # the numpy array containing all the row/line 
                  # indices where the value is = 1.
#array([0, 1])

The above tells you that there is a value = 1 in the first (0) and second (1) row of the matrix A .

Next:

np.where(A==1)[0][0]
0

returns the index of the first line that contains a value = 1. 0 here is the first line of matrix A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM