Skip to content

Commit 99e1382

Browse files
committed
Add non-numeric index example for loc slice step behavior
1 parent 8a4d720 commit 99e1382

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

doc/source/user_guide/indexing.rst

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -431,23 +431,35 @@ 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-
Also, when using a slice with a step, such as ``.loc[start:stop:step]``, note that
434+
When using a slice with a step, such as ``.loc[start:stop:step]``, note that
435435
*start* and *stop* are interpreted as **labels**, while *step* is applied over
436436
the **positional index** within that label range. This means a stepped slice
437-
may return different labels than selecting an explicit list, even when they
438-
appear similar.
437+
will behave differently than using the labels ``range(start, stop, step)`` when
438+
the index is not contiguous integers.
439439

440440
For example, in a ``Series`` with a non-contiguous integer index:
441441

442442
.. ipython:: python
443443
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
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
447447
448448
The first applies *step* across **positional locations** between the start/stop
449449
labels. The second selects each label directly.
450450

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+
451463

452464
.. _indexing.integer:
453465

0 commit comments

Comments
 (0)