基于标签与基于位置的访问
自信地选择 loc 或 iloc
基于标签与基于位置的访问 是 CoddyKit 上的免费 Data Science Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Data Science Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Data Science Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Two Ways to Reach In
A Series has both labels and positions, so there are two ways to grab a value: by its label or by its position number. Knowing which to use keeps your code clear. 🎯
Our Sample Series
Here is a small Series with string labels. We will use it to compare both access styles throughout this lesson.
import pandas as pd
s = pd.Series([90, 75, 88], index=['Ada', 'Bo', 'Cy'])loc Uses Labels
The .loc accessor looks values up by their index label. You ask for a name and pandas returns that named value.
print(s.loc['Bo'])iloc Uses Positions
The .iloc accessor works by integer position instead, counting from zero like a normal list. Position 1 is the second value.
print(s.iloc[1])Same Value, Two Roads
With our Series, s.loc['Bo'] and s.iloc[1] return the same number. They reach it differently: one by name, one by spot.
print(s.loc['Bo'] == s.iloc[1])Slicing With iloc
Position slices behave like list slices: the end is excluded. So iloc[0:2] returns the first two values only.
print(s.iloc[0:2])Slicing With loc
Label slices are different: with .loc, the end label is included. Asking from 'Ada' to 'Bo' returns both endpoints.
print(s.loc['Ada':'Bo'])The Inclusive Surprise
That inclusive end is the most common mix-up. Remember: iloc drops the last position, while loc keeps the last label. 🧠
Grab Several at Once
Pass a list of labels to .loc to pull many values together. The result is a smaller Series in the order you asked.
print(s.loc[['Ada', 'Cy']])When Labels Are Numbers
If your index is integers, plain s[2] gets ambiguous. Using explicit .loc or .iloc removes all doubt about what you meant.
Pick With Confidence
Reach for .loc when you know the name, and .iloc when you know the spot. Being explicit makes your selections impossible to misread.
Quick Check
Test your grip on the two accessors.
Recap
You now choose .loc for labels and .iloc for positions, and you remember that loc slices include the end while iloc slices do not. Solid! 🎉
常见问题解答
「基于标签与基于位置的访问」课时是免费的吗?
是的 — 「基于标签与基于位置的访问」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Data Science Academy 课程的其余内容,请升级到 CoddyKit PRO。 Data Science Academy 课程共包含 4 节课。
「基于标签与基于位置的访问」这节课中我会学到什么?
自信地选择 loc 或 iloc 你通过在浏览器中直接运行的动手代码来练习 Data Science Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Data Science Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Data Science Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「基于标签与基于位置的访问」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Data Science Academy 课中编写并运行代码吗?
能。每节 Data Science Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 带名称和索引的列
- 基于标签与基于位置的访问
- Series 运算与对齐
- 计数并发现值