Python Numpy数组:为何两独立数组可通过索引关联筛选数据?
Great question! Let me break down exactly what's happening here, step by step.
First, let's clarify what np_positions == 'GK' does. When you run this comparison on a NumPy array, it returns a boolean array (an array of True/False values) with the exact same length as np_positions. Each entry in this boolean array corresponds to the index in the original array:
Truemeans the element at that index innp_positionsis'GK'Falsemeans it's any other position
For example, if we use a simplified version of your data:
import numpy as np positions = ['GK', 'M', 'GK', 'D'] heights = [191, 184, 190, 180] np_positions = np.array(positions) np_heights = np.array(heights) bool_mask = np_positions == 'GK' print(bool_mask) # Output: [ True False True False]
Now, when you use this boolean array to index np_heights (like np_heights[bool_mask]), NumPy doesn't care that np_heights and np_positions are "separate" arrays. What it cares about is:
- The boolean mask has the same length as
np_heights - Each
Truein the mask tells NumPy to keep the element at that same index innp_heights
Since you created both arrays from lists where each index corresponds to the same player, the boolean mask's True positions directly map to the indices of the goalkeepers' heights in np_heights. That's why the code correctly pulls out all the goalkeeper heights.
To put it simply: The magic isn't that NumPy "knows" the arrays are linked—it's that the boolean mask acts as a set of index markers, and both arrays share the same index-to-player mapping because you built them from corresponding lists.
内容的提问来源于stack exchange,提问作者Mish Akopyan

