diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt index de6c20a292eac..c72334c5910a9 100755 --- a/doc/source/whatsnew/v0.17.1.txt +++ b/doc/source/whatsnew/v0.17.1.txt @@ -169,7 +169,7 @@ Bug Fixes - +- Bug in indexing with a ``range``, (:issue:`11652`) - Bug in ``to_sql`` using unicode column names giving UnicodeEncodeError with (:issue:`11431`). diff --git a/pandas/core/index.py b/pandas/core/index.py index b0cd72e572c09..cdd0de4e1196d 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -1755,7 +1755,8 @@ def get_loc(self, key, method=None, tolerance=None): if tolerance is not None: raise ValueError('tolerance argument only valid if using pad, ' 'backfill or nearest lookups') - return self._engine.get_loc(_values_from_object(key)) + key = _values_from_object(key) + return self._engine.get_loc(key) indexer = self.get_indexer([key], method=method, tolerance=tolerance) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 25a110ee43039..2b1cb0a1e1b31 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -104,6 +104,8 @@ def _get_setitem_indexer(self, key): if isinstance(key, tuple) and not self.ndim < len(key): return self._convert_tuple(key, is_setter=True) + if isinstance(key, range): + return self._convert_range(key, is_setter=True) try: return self._convert_to_indexer(key, is_setter=True) @@ -156,6 +158,10 @@ def _convert_tuple(self, key, is_setter=False): keyidx.append(idx) return tuple(keyidx) + def _convert_range(self, key, is_setter=False): + """ convert a range argument """ + return list(key) + def _convert_scalar_indexer(self, key, axis): # if we are accessing via lowered dim, use the last dim ax = self.obj._get_axis(min(axis, self.ndim - 1)) diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index e24edbeae68ef..cb06b714d4700 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -4726,6 +4726,17 @@ def test_indexing_dtypes_on_empty(self): assert_series_equal(df2.loc[:,'a'], df2.iloc[:,0]) assert_series_equal(df2.loc[:,'a'], df2.ix[:,0]) + def test_range_in_series_indexing(self): + # range can cause an indexing error + # GH 11652 + for x in [5, 999999, 1000000]: + s = pd.Series(index=range(x)) + s.loc[range(1)] = 42 + assert_series_equal(s.loc[range(1)],Series(42.0,index=[0])) + + s.loc[range(2)] = 43 + assert_series_equal(s.loc[range(2)],Series(43.0,index=[0,1])) + @slow def test_large_dataframe_indexing(self): #GH10692