使用布尔掩码进行选择
使用条件筛选值
使用布尔掩码进行选择 是 CoddyKit 上的免费 Data Science Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Data Science Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Data Science Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Compare a Whole Array
Write a comparison and NumPy applies it to every element at once. The result is a boolean array of True and False values.
a = np.array([5, 12, 7, 20])
a > 10 # [False True False True]That Result Is a Mask
This array of True and False is a mask. Each position marks whether that element passed your condition.
Filter With the Mask
Put the mask in square brackets to keep only the True positions. NumPy returns just the elements that matched.
a[a > 10] # [12 20]One Line, No Loop
This replaces a manual loop with one expression. Boolean filtering is faster to write and far faster to run on big arrays.
Combine Conditions
Join masks with & for and and the pipe for or. Each condition must sit inside its own parentheses.
a[(a > 5) & (a < 20)] # [12 7]Mind the Parentheses
Without parentheses around each condition, Python applies operators in the wrong order and raises an error. Wrap every comparison.
Flip With the Tilde
The ~ operator inverts a mask, turning True into False. Use it to select everything that did not match your condition.
a[~(a > 10)] # [5 7]Count the Matches
Booleans act like 1 and 0, so sum on a mask counts how many elements passed. It is a quick way to size a subset.
(a > 10).sum() # 2Check Any or All
Use any to ask if at least one element matched, and all to ask if every element did. Both return a single True or False.
(a > 0).all() # TrueAssign Through a Mask
A mask can target elements for assignment, not just reading. Here every value above 10 is capped at 10 in place.
a[a > 10] = 10Masks Power Data Cleaning
From dropping outliers to fixing bad entries, masks are how data scientists select and edit exactly the values they care about.
Quick Check
You want values both above 5 and below 20.
Mask Recap
You built boolean masks, filtered and counted with them, combined conditions safely, and even assigned through them. That is selection mastery. ✨
常见问题解答
「使用布尔掩码进行选择」课时是免费的吗?
是的 — 「使用布尔掩码进行选择」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Data Science Academy 课程的其余内容,请升级到 CoddyKit PRO。 Data Science Academy 课程共包含 4 节课。
「使用布尔掩码进行选择」这节课中我会学到什么?
使用条件筛选值 你通过在浏览器中直接运行的动手代码来练习 Data Science Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Data Science Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Data Science Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「使用布尔掩码进行选择」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Data Science Academy 课中编写并运行代码吗?
能。每节 Data Science Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。