@@ -242,6 +242,44 @@ Label-based slicing conventions
242
242
Non-monotonic indexes require exact matches
243
243
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
244
244
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
+
245
283
Endpoints are inclusive
246
284
~~~~~~~~~~~~~~~~~~~~~~~
247
285
0 commit comments