Label-Based and Position-Based Access
Retrieve elements with .loc (label) and .iloc (integer position) and understand the difference between the two.
Two Ways to Access Series Elements
Pandas provides two primary accessors for selecting elements from a Series: .loc for label-based access and .iloc for integer position-based access. Understanding which to use and when is critical — using the wrong one on an integer-indexed Series produces confusing results, and Pandas 2.0 deprecated many ambiguous direct bracket usages.
import pandas as pd
s = pd.Series([10, 20, 30], index=['a', 'b', 'c'])
print(s.loc['b']) # 20 -- by label
print(s.iloc[1]) # 20 -- by position.loc: Label-Based Access
.loc accesses elements by their index label. You can pass a single label (returns a scalar), a list of labels (returns a Series), or a slice of labels (inclusive on both ends, unlike Python slices). If the label does not exist, Pandas raises a KeyError. Use .loc when labels are meaningful (dates, names, IDs).
import pandas as pd
s = pd.Series([10, 20, 30, 40, 50],
index=['a', 'b', 'c', 'd', 'e'])
print(s.loc['c']) # 30
print(s.loc[['a', 'c']]) # a:10 c:30
print(s.loc['b':'d']) # b:20 c:30 d:40 -- inclusiveAll lessons in this course
- Creating a Series
- Label-Based and Position-Based Access
- Vectorized Operations on Series
- Useful Series Methods