简体   繁体   中英

Can you explaing now this works. Python Numpy.arrays working with regular lists

positions = ['GK', 'M', 'A', 'D', ...]
heights = [191, 184, 185, 180, ...]

Each element in the lists corresponds to a player. The first list, positions, contains strings representing each player's position. The possible positions are: 'GK' (goalkeeper), 'M' (midfield), 'A' (attack) and 'D' (defense). The second list, heights , contains integers representing the height of the player in cm.

1) First I Convert positions and heights to numpy arrays:

np_heights = np.array(heights)
np_positions = np.array(positions)

Then I find out the Heights of the goalkeepers: gk_heights

gk_heights = np_heights[np_positions =='GK'] 

This code works fine and does what it should do.

Now the question.

isn't np_heights and np_positions two separate lists. how does this line :

gk_heights = np_heights[np_positions =='GK']

know that a certain index in np_positions is associated to a certain index in np_heights ?

This is the last question from Data Camp online course: URL: https://campus.datacamp.com/courses/intro-to-python-for-data-science/chapter-4-numpy?ex=16

Any help would be appreciated.

The answer to this question is tied to what the expression np_positions=='GK' means. You should try running only this line to see what the output is. Essentially, the output of this line is a boolean array of the same shape as np_positions and elements of the boolean array are True where the conditional is satisfied and False where the conditional is not satisfied. So, you should get an array back like np_positions=='GK' = array([True,False,False,False...]) . And then when you use this array as an index slice into np_heights , the expression np_heights[np_positions=='GK'] tells you to "pick out the values of np_heights where the inside array, np_positions=='GK' , is True . And so, it will pick out the first element of np_heights . Hopefully this explanation made sense.

What should be learned from this explanation is that your two arrays better be in the same order . The two arrays don't communicate to each other on which player gets put in which index. The expression np_heights[np_positions=='GK'] says in human words: "where in np_positions is(are) the goal keeper(s)? Oh it's in index 0 (or others?) - return the index 0 value of np_height .

Thus, if goal keeper is the first element of one array, it better be the first element of the second array (and so on and so forth) in order for this expression to work out right.

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