← Back to Pandas Course | Chapter 2: Series | Lesson 3 of 7

Series slicing

Slicing takes a range of items; positional slices exclude the end while label slices include it.

In this page:

  1. Series slicing
Syntax
python
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

python
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
  1. Expecting label slices to exclude the end
  2. Slicing with the wrong indexer type
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.