Skip to content

Commit f6d0d08

Browse files
nileracecrewjreback
authored andcommitted
DOC: examples of label-based slicing of monotonic and non-monotonic indexes
closes pandas-dev#12522
1 parent 3bed097 commit f6d0d08

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

doc/source/gotchas.rst

+38
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,44 @@ Label-based slicing conventions
242242
Non-monotonic indexes require exact matches
243243
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
244244

245+
If the index of a ``Series`` or ``DataFrame`` is monotonically increasing or decreasing, then the bounds
246+
of a label-based slice can be outside the range of the index, much like slice indexing a
247+
normal Python ``list``. Monotonicity of an index can be tested with the ``is_monotonic_increasing`` and
248+
``is_monotonic_decreasing`` attributes.
249+
250+
.. ipython:: python
251+
252+
df = pd.DataFrame(index=[2,3,3,4,5], columns=['data'], data=range(5))
253+
df.index.is_monotonic_increasing
254+
255+
# no rows 0 or 1, but still returns rows 2, 3 (both of them), and 4:
256+
df.loc[0:4, :]
257+
258+
# slice is are outside the index, so empty DataFrame is returned
259+
df.loc[13:15, :]
260+
261+
On the other hand, if the index is not monotonic, then both slice bounds must be
262+
*unique* members of the index.
263+
264+
.. ipython:: python
265+
266+
df = pd.DataFrame(index=[2,3,1,4,3,5], columns=['data'], data=range(6))
267+
df.index.is_monotonic_increasing
268+
269+
# OK because 2 and 4 are in the index
270+
df.loc[2:4, :]
271+
272+
.. code-block:: python
273+
274+
# 0 is not in the index
275+
In [9]: df.loc[0:4, :]
276+
KeyError: 0
277+
278+
# 3 is not a unique label
279+
In [11]: df.loc[2:3, :]
280+
KeyError: 'Cannot get right slice bound for non-unique label: 3'
281+
282+
245283
Endpoints are inclusive
246284
~~~~~~~~~~~~~~~~~~~~~~~
247285

0 commit comments

Comments
 (0)