Skip to content

Commit

Permalink
BUG: Fix IntervalIndex.insert to allow inserting NaN
Browse files Browse the repository at this point in the history
  • Loading branch information
jschendel committed Nov 16, 2017
1 parent fe1bfd7 commit 3c933ad
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 8 deletions.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.21.1.txt
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ Bug Fixes
- Bug in ``pd.Series.rolling.skew()`` and ``rolling.kurt()`` with all equal values has floating issue (:issue:`18044`)
- Bug in ``pd.DataFrameGroupBy.count()`` when counting over a datetimelike column (:issue:`13393`)
- Bug in ``pd.concat`` when empty and non-empty DataFrames or Series are concatenated (:issue:`18178` :issue:`18187`)
- Bug in ``IntervalIndex.insert`` when attempting to insert ``NaN`` (:issue:`18295`)

Conversion
^^^^^^^^^^
Expand Down
23 changes: 15 additions & 8 deletions pandas/core/indexes/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -979,14 +979,21 @@ def delete(self, loc):
return self._shallow_copy(new_left, new_right)

def insert(self, loc, item):
if not isinstance(item, Interval):
raise ValueError('can only insert Interval objects into an '
'IntervalIndex')
if not item.closed == self.closed:
raise ValueError('inserted item must be closed on the same side '
'as the index')
new_left = self.left.insert(loc, item.left)
new_right = self.right.insert(loc, item.right)
if isinstance(item, Interval):
if not item.closed == self.closed:
raise ValueError('inserted item must be closed on the same '
'side as the index')
left_insert = item.left
right_insert = item.right
elif is_scalar(item) and isna(item):
# GH 18295
left_insert = right_insert = item
else:
raise ValueError('can only insert Interval objects and NaN into '
'an IntervalIndex')

new_left = self.left.insert(loc, left_insert)
new_right = self.right.insert(loc, right_insert)
return self._shallow_copy(new_left, new_right)

def _as_like_interval_index(self, other, error_msg):
Expand Down
5 changes: 5 additions & 0 deletions pandas/tests/indexes/test_interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,11 @@ def test_insert(self):
pytest.raises(ValueError, self.index.insert, 0,
Interval(2, 3, closed='left'))

# GH 18295
expected = self.index_with_nan
result = self.index.insert(1, np.nan)
tm.assert_index_equal(result, expected)

def test_take(self):
actual = self.index.take([0, 1])
assert self.index.equals(actual)
Expand Down

0 comments on commit 3c933ad

Please sign in to comment.