Skip to content

Commit aa5bf6d

Browse files
nileracecrewEric Lawrence
authored and
Eric Lawrence
committed
DOC: examples of label-based slicing of monotonic and non-monotonic indexes
1 parent c69037c commit aa5bf6d

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

doc/source/gotchas.rst

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,40 @@ 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+
# no rows 0 or 1, but still returns rows 2, 3 (both of them), and 4:
255+
df.loc[0:4, :]
256+
# slice is are outside the index, so empty DataFrame is returned
257+
df.loc[13:15, :]
258+
259+
On the other hand, if the index is not monotonic, then both slice bounds must be
260+
*unique* members of the index.
261+
262+
.. ipython:: python
263+
264+
df = pd.DataFrame(index=[2,3,1,4,3,5], columns=['data'], data=range(6))
265+
df.index.is_monotonic_increasing
266+
# OK because 2 and 4 are in the index
267+
df.loc[2:4, :]
268+
# 0 is not in the index
269+
try:
270+
df.loc[0:4, :]
271+
except Exception as e:
272+
print e.__class__.__name__ + ': ' + str(e)
273+
# 3 is not a unique label
274+
try:
275+
df.loc[2:3, :]
276+
except Exception as e:
277+
print e.__class__.__name__ + ': ' + str(e)
278+
245279
Endpoints are inclusive
246280
~~~~~~~~~~~~~~~~~~~~~~~
247281

0 commit comments

Comments
 (0)