Skip to content

Commit

Permalink
NA Compat
Browse files Browse the repository at this point in the history
  • Loading branch information
jschendel committed Nov 16, 2017
1 parent 3c933ad commit 237766c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
8 changes: 6 additions & 2 deletions pandas/core/indexes/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
23 changes: 21 additions & 2 deletions pandas/tests/indexes/test_interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 237766c

Please sign in to comment.