You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Numpy数组:为何两独立数组可通过索引关联筛选数据?

Why does this NumPy indexing work with two separate arrays?

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:

  • True means the element at that index in np_positions is 'GK'
  • False means 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:

  1. The boolean mask has the same length as np_heights
  2. Each True in the mask tells NumPy to keep the element at that same index in np_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:35:26