Skip to content

DOC: Examples of monotonic/non-monotonic label-based indexing #12522

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions doc/source/gotchas.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
~~~~~~~~~~~~~~~~~~~~~~~

Expand Down