From eee2b1731d6f385ab703837eda5279acac49dcd5 Mon Sep 17 00:00:00 2001 From: Jean-Mathieu Deschenes Date: Thu, 8 Jun 2017 09:40:32 -0400 Subject: [PATCH] BUG: TimedeltaIndex raising ValueError when slice indexing (#16637) closes #16637 --- doc/source/whatsnew/v0.20.2.txt | 1 + pandas/core/indexes/timedeltas.py | 3 +-- pandas/tests/indexing/test_timedelta.py | 17 +++++++++++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index 31125db0f34d4..f1093e712aeb9 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -51,6 +51,7 @@ Bug Fixes - Bug in :func:`unique` on an array of tuples (:issue:`16519`) - Bug in :func:`cut` when ``labels`` are set, resulting in incorrect label ordering (:issue:`16459`) - Fixed a compatibility issue with IPython 6.0's tab completion showing deprecation warnings on ``Categoricals`` (:issue:`16409`) +- Bug in ``TimedeltaIndex`` raising a ``ValueError`` when slice indexing with ``loc`` (:issue:`16637`) Conversion ^^^^^^^^^^ diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index ab94a5bffb4f9..c025c74625972 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -680,8 +680,7 @@ def get_loc(self, key, method=None, tolerance=None): ------- loc : int """ - - if is_bool_indexer(key): + if is_bool_indexer(key) or is_timedelta64_dtype(key): raise TypeError if isnull(key): diff --git a/pandas/tests/indexing/test_timedelta.py b/pandas/tests/indexing/test_timedelta.py index cf8cc6c2d345d..5cba019e6e02d 100644 --- a/pandas/tests/indexing/test_timedelta.py +++ b/pandas/tests/indexing/test_timedelta.py @@ -18,3 +18,20 @@ def test_boolean_indexing(self): index=pd.to_timedelta(range(10), unit='s'), columns=['x']) tm.assert_frame_equal(expected, result) + + def test_slice_indexing(self): + # GH 16637 + df = pd.DataFrame({'x': range(10)}) + df.index = pd.to_timedelta(range(10), unit='s') + + conditions = [df.index[0], df.index[4:8], df.index[[3, 5]]] + expected_data = [[20, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [0, 1, 2, 3, 20, 20, 20, 20, 8, 9], + [0, 1, 2, 20, 4, 20, 6, 7, 8, 9]] + for cond, data in zip(conditions, expected_data): + result = df.copy() + result.loc[cond, 'x'] = 20 + expected = pd.DataFrame(data, + index=pd.to_timedelta(range(10), unit='s'), + columns=['x']) + tm.assert_frame_equal(expected, result)