数组索引与切片
提取行、列和范围
数组索引与切片 是 CoddyKit 上的免费 Data Science Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Data Science Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Data Science Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Grab the Pieces You Need
Real analysis means pulling out parts of your data. NumPy's indexing lets you grab single values, rows, columns, or ranges with ease. ✂️
Single Elements by Position
Just like a list, you reach one element by its index. Counting starts at zero, so arr[0] is the very first value.
arr = np.array([10, 20, 30])
arr[0] # 10Count From the End
Negative indices count backward. arr[-1] hands you the last element without needing to know the array's length.
arr[-1] # 30Slices Grab a Range
A slice uses start:stop to pull a range. The start is included, the stop is not, just like Python lists.
np.arange(10)[2:5] # 2 3 4Steps Inside a Slice
Add a third number for a step. Using ::2 keeps every other element, an easy way to thin out data.
np.arange(10)[::2] # 0 2 4 6 8Two Dimensions, One Bracket
For a 2D array, give row and column in one bracket: arr[row, col]. This is cleaner than chaining two sets of brackets.
m = np.array([[1, 2], [3, 4]])
m[1, 0] # 3Grab a Whole Row
A lone colon means take everything along that axis. So m[0, :] returns the entire first row.
m[0, :] # array([1, 2])Grab a Whole Column
Flip it to pull a column. m[:, 0] sweeps every row and keeps just the first column's values.
m[:, 0] # array([1, 3])Slices Are Views, Not Copies
Careful: a slice is a view into the original. Change the slice and the source array changes too, which can surprise you.
s = arr[0:2]
s[0] = 99 # arr also changesMake a Real Copy
When you need independence, call copy. It hands back a separate array so edits never touch the original.
safe = arr[0:2].copy()Slice to Assign, Too
Indexing works on the left side as well. Assign to a slice and you update a whole range in one move.
arr[0:2] = 0 # first two become 0Quick Check
Let's test selecting a column from a 2D array.
Recap
You can now carve up arrays: index single values, slice ranges with steps, target rows and columns, and copy when you need to stay safe. 🎉
常见问题解答
「数组索引与切片」课时是免费的吗?
是的 — 「数组索引与切片」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Data Science Academy 课程的其余内容,请升级到 CoddyKit PRO。 Data Science Academy 课程共包含 4 节课。
「数组索引与切片」这节课中我会学到什么?
提取行、列和范围 你通过在浏览器中直接运行的动手代码来练习 Data Science Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Data Science Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Data Science Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「数组索引与切片」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Data Science Academy 课中编写并运行代码吗?
能。每节 Data Science Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。