Skip to content

Commit

Permalink
BUG: fix integer-slicing from integers-as-floats, GH #670
Browse files Browse the repository at this point in the history
  • Loading branch information
wesm committed Jan 24, 2012
1 parent e66d25e commit b3b5140
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
15 changes: 9 additions & 6 deletions pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ def _convert_to_indexer(self, obj, axis=0):
is_int_index = _is_integer_index(labels)
if isinstance(obj, slice):

int_slice = _is_integer_slice(obj)
int_slice = _is_index_slice(obj)
null_slice = obj.start is None and obj.stop is None
# could have integers in the first level of the MultiIndex
position_slice = (int_slice
Expand All @@ -234,7 +234,7 @@ def _convert_to_indexer(self, obj, axis=0):
i, j = labels.slice_locs(obj.start, obj.stop)
slicer = slice(i, j, obj.step)
except Exception:
if _is_integer_slice(obj):
if _is_index_slice(obj):
if labels.inferred_type == 'integer':
raise
slicer = obj
Expand Down Expand Up @@ -276,7 +276,7 @@ def _get_slice_axis(self, slice_obj, axis=0):
axis_name = obj._get_axis_name(axis)
labels = getattr(obj, axis_name)

int_slice = _is_integer_slice(slice_obj)
int_slice = _is_index_slice(slice_obj)

null_slice = slice_obj.start is None and slice_obj.stop is None
# could have integers in the first level of the MultiIndex
Expand All @@ -289,7 +289,7 @@ def _get_slice_axis(self, slice_obj, axis=0):
i, j = labels.slice_locs(slice_obj.start, slice_obj.stop)
slicer = slice(i, j, slice_obj.step)
except Exception:
if _is_integer_slice(slice_obj):
if _is_index_slice(slice_obj):
if labels.inferred_type == 'integer':
raise
slicer = slice_obj
Expand All @@ -301,9 +301,12 @@ def _get_slice_axis(self, slice_obj, axis=0):

return self._slice(slicer, axis=axis)

def _is_integer_slice(obj):
def _is_index_slice(obj):
def _is_valid_index(x):
return com.is_integer(x) or com.is_float(x) and np.allclose(x, int(x))

def _crit(v):
return v is None or com.is_integer(v)
return v is None or _is_valid_index(v)

both_none = obj.start is None and obj.stop is None

Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,17 @@ def test_slice_can_reorder_not_uniquely_indexed(self):
s = Series(1, index=['a', 'a', 'b', 'b', 'c'])
result = s[::-1] # it works!

def test_slice_float_get_set(self):
result = self.ts[4.0:10.0]
expected = self.ts[4:10]
assert_series_equal(result, expected)

self.ts[4.0:10.0] = 0
self.assert_((self.ts[4:10] == 0).all())

self.assertRaises(TypeError, self.ts.__getitem__, slice(4.5, 10.0))
self.assertRaises(TypeError, self.ts.__setitem__, slice(4.5, 10.0), 0)

def test_setitem(self):
self.ts[self.ts.index[5]] = np.NaN
self.ts[[1,2,17]] = np.NaN
Expand Down

0 comments on commit b3b5140

Please sign in to comment.