diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index d7feb6e547b22..df31c609d50bb 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -182,6 +182,8 @@ Other Enhancements - :func:`to_timedelta` now supports iso-formated timedelta strings (:issue:`21877`) - :class:`Series` and :class:`DataFrame` now support :class:`Iterable` in constructor (:issue:`2193`) - :class:`DatetimeIndex` gained :attr:`DatetimeIndex.timetz` attribute. Returns local time with timezone information. (:issue:`21358`) +- Implement interpolating ``NaT`` values in ``datetime`` series (:issue:`11701`) +- .. _whatsnew_0240.api_breaking: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 9bdf34113ccf0..e0be913199a92 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6316,6 +6316,14 @@ def interpolate(self, method='linear', axis=0, limit=None, inplace=False, raise NotImplementedError("Interpolation with NaNs in the index " "has not been implemented. Try filling " "those NaNs before interpolating.") + is_datetime = False + datetime_timezone = None + if is_datetime64_any_dtype(_maybe_transposed_self): + _datetime_nat_values = _maybe_transposed_self.isnull() + datetime_timezone = _maybe_transposed_self.dt.tz + _maybe_transposed_self = _maybe_transposed_self.astype('int') + _maybe_transposed_self[_datetime_nat_values] = np.nan + is_datetime = True data = _maybe_transposed_self._data new_data = data.interpolate(method=method, axis=ax, index=index, values=_maybe_transposed_self, limit=limit, @@ -6324,6 +6332,11 @@ def interpolate(self, method='linear', axis=0, limit=None, inplace=False, inplace=inplace, downcast=downcast, **kwargs) + if is_datetime: + new_data = self._constructor(new_data) + new_data = pd.to_datetime(new_data, utc=True).dt.tz_convert( + datetime_timezone) + if inplace: if axis == 1: new_data = self._constructor(new_data).T._data diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py index ab3fdd8cbf84f..21a2a850549d1 100644 --- a/pandas/tests/series/test_missing.py +++ b/pandas/tests/series/test_missing.py @@ -1317,3 +1317,16 @@ def test_series_interpolate_intraday(self): result = ts.reindex(new_index).interpolate(method='time') tm.assert_numpy_array_equal(result.values, exp.values) + + @pytest.mark.parametrize("inplace", [True, False]) + def test_series_interpolate_nat(self, tz_naive_fixture, inplace): + # GH 11701 + expected = pd.Series(pd.date_range('2015-01-01', + '2015-01-30', tz=tz_naive_fixture)) + result = expected.copy() + result[[3, 4, 5, 13, 14, 15]] = pd.NaT + if inplace: + result.interpolate(inplace=inplace) + else: + result = result.interpolate() + tm.assert_series_equal(result, expected)