Skip to content

Commit 43ca059

Browse files
authored
DOC: clarify loc slice step behavior with example closes #63311 (#63346)
1 parent cf2349c commit 43ca059

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

doc/source/user_guide/indexing.rst

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,36 @@ an error will be raised. For instance, in the above example, ``s.loc[2:5]`` woul
431431
For more information about duplicate labels, see
432432
:ref:`Duplicate Labels <duplicates>`.
433433

434+
When using a slice with a step, such as ``.loc[start:stop:step]``, note that
435+
*start* and *stop* are interpreted as **labels**, while *step* is applied over
436+
the **positional index** within that label range. This means a stepped slice
437+
will behave differently than using the labels ``range(start, stop, step)`` when
438+
the index is not contiguous integers.
439+
440+
For example, in a ``Series`` with a non-contiguous integer index:
441+
442+
.. ipython:: python
443+
444+
s = pd.Series(range(10), index=[0, 5, 10, 15, 20, 25, 30, 35, 40, 45])
445+
s.loc[10:50:5] # (10), then skip 3 positions → 35 only
446+
s.loc[[10, 15, 20, 25]] # explicit label selection
447+
448+
The first applies *step* across **positional locations** between the start/stop
449+
labels. The second selects each label directly.
450+
451+
Similarly, with a string-based index, the behavior is identical:
452+
453+
.. ipython:: python
454+
455+
s = pd.Series(range(10), index=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'])
456+
s.loc['b':'i':2] # Start at 'b' (position 1), stop at 'i' (position 8), step 2 positions → 'b', 'd', 'f', 'h'
457+
s.loc[['b', 'd', 'f', 'h']] # explicit label selection
458+
459+
In both cases, *start* and *stop* determine the label boundaries (inclusive),
460+
while *step* skips positions within that range, regardless of the index type.
461+
462+
463+
434464
.. _indexing.integer:
435465

436466
Selection by position

0 commit comments

Comments
 (0)