Skip to content

Commit e103ae0

Browse files
committed
BUG: Fix IntervalIndex.insert to allow inserting NaN
1 parent 412988e commit e103ae0

File tree

2 files changed

+20
-8
lines changed

2 files changed

+20
-8
lines changed

pandas/core/indexes/interval.py

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1001,14 +1001,21 @@ def delete(self, loc):
10011001
return self._shallow_copy(new_left, new_right)
10021002

10031003
def insert(self, loc, item):
1004-
if not isinstance(item, Interval):
1005-
raise ValueError('can only insert Interval objects into an '
1006-
'IntervalIndex')
1007-
if not item.closed == self.closed:
1008-
raise ValueError('inserted item must be closed on the same side '
1009-
'as the index')
1010-
new_left = self.left.insert(loc, item.left)
1011-
new_right = self.right.insert(loc, item.right)
1004+
if isinstance(item, Interval):
1005+
if not item.closed == self.closed:
1006+
raise ValueError('inserted item must be closed on the same '
1007+
'side as the index')
1008+
left_insert = item.left
1009+
right_insert = item.right
1010+
elif is_scalar(item) and isna(item):
1011+
# GH 18295
1012+
left_insert = right_insert = item
1013+
else:
1014+
raise ValueError('can only insert Interval objects and NaN into '
1015+
'an IntervalIndex')
1016+
1017+
new_left = self.left.insert(loc, left_insert)
1018+
new_right = self.right.insert(loc, right_insert)
10121019
return self._shallow_copy(new_left, new_right)
10131020

10141021
def _as_like_interval_index(self, other, error_msg):

pandas/tests/indexes/test_interval.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,11 @@ def test_insert(self):
375375
pytest.raises(ValueError, self.index.insert, 0,
376376
Interval(2, 3, closed='left'))
377377

378+
# GH 18295
379+
expected = self.index_with_nan
380+
result = self.index.insert(1, np.nan)
381+
tm.assert_index_equal(result, expected)
382+
378383
def test_take(self, closed):
379384
index = self.create_index(closed=closed)
380385

0 commit comments

Comments
 (0)