diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 3f300deddebeb..cfaf8718544ca 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -303,6 +303,7 @@ Indexing - :func:`Index.to_series` now accepts ``index`` and ``name`` kwargs (:issue:`18699`) - :func:`DatetimeIndex.to_series` now accepts ``index`` and ``name`` kwargs (:issue:`18699`) - Bug in indexing non-scalar value from ``Series`` having non-unique ``Index`` will return value flattened (:issue:`17610`) +- Bug in :func:`DatetimeIndex.insert` where inserting ``NaT`` into a timezone-aware index incorrectly raised (:issue:`16357`) I/O diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index bec26ef72d63a..3fc3cf9a78a25 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -1775,7 +1775,7 @@ def insert(self, loc, item): if isinstance(item, (datetime, np.datetime64)): self._assert_can_do_op(item) - if not self._has_same_tz(item): + if not self._has_same_tz(item) and not isna(item): raise ValueError( 'Passed item and index have different timezone') # check freq can be preserved on edge cases diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py index b3ce22962d5d4..48ceefd6368c0 100644 --- a/pandas/tests/indexes/datetimes/test_indexing.py +++ b/pandas/tests/indexes/datetimes/test_indexing.py @@ -46,6 +46,15 @@ def test_where_tz(self): expected = i2 tm.assert_index_equal(result, expected) + @pytest.mark.parametrize('null', [None, np.nan, pd.NaT]) + @pytest.mark.parametrize('tz', [None, 'UTC', 'US/Eastern']) + def test_insert_nat(self, tz, null): + # GH#16537, GH#18295 (test missing) + idx = pd.DatetimeIndex(['2017-01-01'], tz=tz) + expected = pd.DatetimeIndex(['NaT', '2017-01-01'], tz=tz) + res = idx.insert(0, null) + tm.assert_index_equal(res, expected) + def test_insert(self): idx = DatetimeIndex( ['2000-01-04', '2000-01-01', '2000-01-02'], name='idx') @@ -145,13 +154,6 @@ def test_insert(self): assert result.tz == expected.tz assert result.freq is None - # GH 18295 (test missing) - expected = DatetimeIndex( - ['20170101', pd.NaT, '20170102', '20170103', '20170104']) - for na in (np.nan, pd.NaT, None): - result = date_range('20170101', periods=4).insert(1, na) - tm.assert_index_equal(result, expected) - def test_delete(self): idx = date_range(start='2000-01-01', periods=5, freq='M', name='idx')