From aa5bf6d16cfe77e06138bbbf0457b674c1248656 Mon Sep 17 00:00:00 2001 From: nileracecrew Date: Thu, 3 Mar 2016 15:45:00 -0800 Subject: [PATCH] DOC: examples of label-based slicing of monotonic and non-monotonic indexes --- doc/source/gotchas.rst | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/doc/source/gotchas.rst b/doc/source/gotchas.rst index fe7ab67b7f759..39044662b5d13 100644 --- a/doc/source/gotchas.rst +++ b/doc/source/gotchas.rst @@ -242,6 +242,40 @@ Label-based slicing conventions Non-monotonic indexes require exact matches ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +If the index of a ``Series`` or ``DataFrame`` is monotonically increasing or decreasing, then the bounds +of a label-based slice can be outside the range of the index, much like slice indexing a +normal Python ``list``. Monotonicity of an index can be tested with the ``is_monotonic_increasing`` and +``is_monotonic_decreasing`` attributes. + +.. ipython:: python + + df = pd.DataFrame(index=[2,3,3,4,5], columns=['data'], data=range(5)) + df.index.is_monotonic_increasing + # no rows 0 or 1, but still returns rows 2, 3 (both of them), and 4: + df.loc[0:4, :] + # slice is are outside the index, so empty DataFrame is returned + df.loc[13:15, :] + +On the other hand, if the index is not monotonic, then both slice bounds must be +*unique* members of the index. + +.. ipython:: python + + df = pd.DataFrame(index=[2,3,1,4,3,5], columns=['data'], data=range(6)) + df.index.is_monotonic_increasing + # OK because 2 and 4 are in the index + df.loc[2:4, :] + # 0 is not in the index + try: + df.loc[0:4, :] + except Exception as e: + print e.__class__.__name__ + ': ' + str(e) + # 3 is not a unique label + try: + df.loc[2:3, :] + except Exception as e: + print e.__class__.__name__ + ': ' + str(e) + Endpoints are inclusive ~~~~~~~~~~~~~~~~~~~~~~~