Skip to content

Commit 3c933ad

Browse files
committed
BUG: Fix IntervalIndex.insert to allow inserting NaN
1 parent fe1bfd7 commit 3c933ad

File tree

3 files changed

+21
-8
lines changed

3 files changed

+21
-8
lines changed

doc/source/whatsnew/v0.21.1.txt

+1
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ Bug Fixes
6262
- Bug in ``pd.Series.rolling.skew()`` and ``rolling.kurt()`` with all equal values has floating issue (:issue:`18044`)
6363
- Bug in ``pd.DataFrameGroupBy.count()`` when counting over a datetimelike column (:issue:`13393`)
6464
- Bug in ``pd.concat`` when empty and non-empty DataFrames or Series are concatenated (:issue:`18178` :issue:`18187`)
65+
- Bug in ``IntervalIndex.insert`` when attempting to insert ``NaN`` (:issue:`18295`)
6566

6667
Conversion
6768
^^^^^^^^^^

pandas/core/indexes/interval.py

+15-8
Original file line numberDiff line numberDiff line change
@@ -979,14 +979,21 @@ def delete(self, loc):
979979
return self._shallow_copy(new_left, new_right)
980980

981981
def insert(self, loc, item):
982-
if not isinstance(item, Interval):
983-
raise ValueError('can only insert Interval objects into an '
984-
'IntervalIndex')
985-
if not item.closed == self.closed:
986-
raise ValueError('inserted item must be closed on the same side '
987-
'as the index')
988-
new_left = self.left.insert(loc, item.left)
989-
new_right = self.right.insert(loc, item.right)
982+
if isinstance(item, Interval):
983+
if not item.closed == self.closed:
984+
raise ValueError('inserted item must be closed on the same '
985+
'side as the index')
986+
left_insert = item.left
987+
right_insert = item.right
988+
elif is_scalar(item) and isna(item):
989+
# GH 18295
990+
left_insert = right_insert = item
991+
else:
992+
raise ValueError('can only insert Interval objects and NaN into '
993+
'an IntervalIndex')
994+
995+
new_left = self.left.insert(loc, left_insert)
996+
new_right = self.right.insert(loc, right_insert)
990997
return self._shallow_copy(new_left, new_right)
991998

992999
def _as_like_interval_index(self, other, error_msg):

pandas/tests/indexes/test_interval.py

+5
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,11 @@ def test_insert(self):
255255
pytest.raises(ValueError, self.index.insert, 0,
256256
Interval(2, 3, closed='left'))
257257

258+
# GH 18295
259+
expected = self.index_with_nan
260+
result = self.index.insert(1, np.nan)
261+
tm.assert_index_equal(result, expected)
262+
258263
def test_take(self):
259264
actual = self.index.take([0, 1])
260265
assert self.index.equals(actual)

0 commit comments

Comments
 (0)