From 237766c3f951dd16c08218d718f89a97870e3210 Mon Sep 17 00:00:00 2001 From: jschendel Date: Wed, 15 Nov 2017 18:32:01 -0700 Subject: [PATCH] NA Compat --- pandas/core/indexes/interval.py | 8 ++++++-- pandas/tests/indexes/test_interval.py | 23 +++++++++++++++++++++-- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index a51e2df67e8145..c4db8f5eca0c8e 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -980,16 +980,20 @@ def delete(self, loc): def insert(self, loc, item): if isinstance(item, Interval): - if not item.closed == self.closed: + if 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 + if item is not self.left._na_value: + raise TypeError('cannot insert with incompatible NA value: ' + 'got {item}, expected {na}' + .format(item=item, na=self.left._na_value)) left_insert = right_insert = item else: - raise ValueError('can only insert Interval objects and NaN into ' + raise ValueError('can only insert Interval objects and NA into ' 'an IntervalIndex') new_left = self.left.insert(loc, left_insert) diff --git a/pandas/tests/indexes/test_interval.py b/pandas/tests/indexes/test_interval.py index 2790fcd0997cf4..d7447d82632a99 100644 --- a/pandas/tests/indexes/test_interval.py +++ b/pandas/tests/indexes/test_interval.py @@ -255,11 +255,30 @@ def test_insert(self): pytest.raises(ValueError, self.index.insert, 0, Interval(2, 3, closed='left')) + @pytest.mark.parametrize('data', [ + interval_range(0, periods=10), + interval_range(1.7, periods=8, freq=2.5), + interval_range(Timestamp('20170101'), periods=12), + interval_range(Timedelta('1 day'), periods=6), + IntervalIndex.from_tuples([('a', 'd'), ('e', 'j'), ('w', 'z')]), + IntervalIndex.from_tuples([(1, 2), ('a', 'z'), (3.14, 6.28)])]) + def test_insert_na(self, data): # GH 18295 - expected = self.index_with_nan - result = self.index.insert(1, np.nan) + valid_na, invalid_na = np.nan, pd.NaT + if data.left._na_value is pd.NaT: + valid_na, invalid_na = invalid_na, valid_na + + # valid insertion + expected = IntervalIndex([data[0], np.nan]).append(data[1:]) + result = data.insert(1, valid_na) tm.assert_index_equal(result, expected) + # invalid insertion + msg = ('cannot insert with incompatible NA value: got {invalid}, ' + 'expected {valid}').format(invalid=invalid_na, valid=valid_na) + with tm.assert_raises_regex(TypeError, msg): + data.insert(1, invalid_na) + def test_take(self): actual = self.index.take([0, 1]) assert self.index.equals(actual)