0Pricing
Pandas & NumPy Academy · 课时

布尔掩码与高级索引

使用布尔条件筛选数组,并通过整数索引数组选择任意元素。

布尔掩码与高级索引 是 CoddyKit 上的免费 Pandas & NumPy Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Pandas & NumPy Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Pandas & NumPy Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Boolean Arrays as Masks

A boolean mask is an array of True/False values. Use it as an index and you keep only the elements marked True — your main filtering tool.

import numpy as np

a = np.array([5, 3, 8, 1, 9, 2, 7])
mask = a > 4
print(mask)       # [ True False  True False  True False  True]
print(a[mask])    # [5 8 9 7]

Compound Boolean Conditions

Build compound filters with & (and), | (or), and ~ (not). Always wrap each condition in parentheses, or precedence will trip you up.

import numpy as np

a = np.array([3, 7, 2, 9, 1, 6, 4, 8])

# Elements between 4 and 8 inclusive
result = a[(a >= 4) & (a <= 8)]
print(result)   # [7 6 4 8]

# Elements less than 3 or greater than 7
result2 = a[(a < 3) | (a > 7)]
print(result2)  # [2 9 1 8]

Modifying Values with Boolean Indexing

You can assign straight to a boolean selection, changing only the matching elements in place. It's the fastest way to cap outliers or fill in missing values.

import numpy as np

a = np.array([5, -3, 8, -1, 2, -7])
a[a < 0] = 0    # zero out negatives in-place
print(a)        # [5 0 8 0 2 0]

# Cap values above 6
a[a > 6] = 6
print(a)        # [5 0 6 0 2 0]

Boolean Masking on 2-D Arrays

A boolean mask on a 2-D array always returns a flat 1-D result. To select whole rows, build a 1-D mask from one column and index along axis 0.

import numpy as np

m = np.array([[1, 5], [3, 2], [8, 4], [6, 7]])
# Select rows where first column > 4
mask = m[:, 0] > 4
print(mask)     # [False False  True  True]
print(m[mask])  # [[8 4] [6 7]]

np.where with Masks

np.where(condition, x, y) keeps the array's shape: it picks x where the condition holds and y elsewhere. Perfect for swapping values without flattening.

import numpy as np

a = np.array([3, -1, 5, -2, 4])
result = np.where(a >= 0, a, 0)  # keep positives, replace negatives
print(result)  # [3 0 5 0 4]

# Recode: above-average -> 'high', else -> 'low'
labels = np.where(a >= a.mean(), 'high', 'low')
print(labels)  # ['high' 'low' 'high' 'low' 'high']

Fancy Indexing Basics

Fancy indexing means passing an array of integer indices to grab specific elements — in any order, with repeats. It always returns a copy.

import numpy as np

a = np.array([10, 20, 30, 40, 50])
idx = np.array([4, 1, 1, 3])
print(a[idx])   # [50 20 20 40]

# 2D index shape -> 2D output
idx2d = np.array([[0, 2], [4, 1]])
print(a[idx2d])  # [[10 30] [50 20]]

Fancy Indexing on 2-D Arrays

On a 2-D array, paired index arrays pick scattered points: m[rows, cols] grabs the element at each (row, col) pair, not a whole sub-matrix.

import numpy as np

m = np.array([[1,  2,  3],
              [4,  5,  6],
              [7,  8,  9]])

# Select elements at (0,2), (1,0), (2,1)
rows = [0, 1, 2]
cols = [2, 0, 1]
print(m[rows, cols])  # [3 4 8]

np.ix_ for Row-Column Grid Selection

np.ix_ selects a sub-matrix at every combination of the rows and columns you list — handy when you want many rows AND many columns, not just pairs.

import numpy as np

m = np.arange(16).reshape(4, 4)
print(m)

# Select rows 0,2 and columns 1,3
ix = np.ix_([0, 2], [1, 3])
print(m[ix])
# [[ 1  3]
#  [ 9 11]]

np.nonzero() and np.argwhere()

np.nonzero returns the indices of non-zero (or True) elements as a tuple per axis. np.argwhere gives the same info stacked as easy-to-read rows.

import numpy as np

a = np.array([0, 3, 0, 5, 0, 7])
print(np.nonzero(a))       # (array([1, 3, 5]),)
print(np.argwhere(a > 0))  # [[1] [3] [5]]

Combining Boolean and Fancy Indexing

Mix the two: use a boolean mask to filter rows, then fancy indexing to reorder columns. Together they filter and rearrange data in one clean step.

import numpy as np

data = np.array([[1, 2, 3],
                 [4, 5, 6],
                 [7, 8, 9]])
scores = np.array([0.9, 0.3, 0.8])

# Keep high-scoring rows, reorder columns to [2, 0, 1]
high = data[scores > 0.5]
reordered = high[:, [2, 0, 1]]
print(reordered)

Performance: Boolean vs Fancy Indexing

Both boolean and fancy indexing return copies. For filtering, a boolean mask is usually the most readable and plenty fast — a great default.

import numpy as np

a = np.random.rand(1_000_000)

# Boolean mask -- readable and fast
result = a[a > 0.5]
print('filtered size:', result.size)  # ~500000

# Equivalent with np.where + fancy index
idx = np.where(a > 0.5)[0]
result2 = a[idx]
print('same result:', np.array_equal(result, result2))

Quick Check

Test your understanding of boolean masking and fancy indexing from this lesson.

Lesson Recap

Well done! Boolean masks filter and copy, np.where keeps the array's shape, and fancy indexing grabs any elements you name. Next: Pandas Series!

常见问题解答

「布尔掩码与高级索引」课时是免费的吗?

是的 — 「布尔掩码与高级索引」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Pandas & NumPy Academy 课程的其余内容,请升级到 CoddyKit PRO。 Pandas & NumPy Academy 课程共包含 4 节课。

「布尔掩码与高级索引」这节课中我会学到什么?

使用布尔条件筛选数组,并通过整数索引数组选择任意元素。 你通过在浏览器中直接运行的动手代码来练习 Pandas & NumPy Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Pandas & NumPy Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Pandas & NumPy Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「布尔掩码与高级索引」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Pandas & NumPy Academy 课中编写并运行代码吗?

能。每节 Pandas & NumPy Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 通用函数(ufunc)
  2. 聚合函数
  3. 广播规则
  4. 布尔掩码与高级索引
← 返回 Pandas & NumPy Academy