Series slicing
Slicing takes a range of items; positional slices exclude the end while label slices include it.
In this page:
Syntax
s.iloc[start:stop]
s.loc["label1":"label2"]
Series slicing
Positional slices such as s.iloc[1:3] follow Python rules and exclude the end. Label slices such as s.loc["a":"c"] include both ends. You can also use steps like s[::2].
Note:
This label-inclusive rule is a famous Pandas gotcha.
Example: Series slicing
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5], index=list("abcde"))
print(s.iloc[1:3])
print(s.loc["b":"d"])
print(s[::2])
# Output:
# b 2
# c 3
# dtype: int64
# b 2
# c 3
# d 4
# dtype: int64
# a 1
# c 3
# e 5
# dtype: int64
Related Topics
Common Mistakes
- Expecting label slices to exclude the end
- Slicing with the wrong indexer type
- Forgetting a slice can be a view
Chapter Summary
- iloc slices exclude the end
- loc slices include the end
- Steps are allowed
- Slices keep index labels
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: