Skip to content

BUG: Implement interpolating NaT values in datetime series #17709

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.21.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ Other Enhancements
- :func:`Categorical.rename_categories` now accepts a dict-like argument as `new_categories` and only updates the categories found in that dict. (:issue:`17336`)
- :func:`read_excel` raises ``ImportError`` with a better message if ``xlrd`` is not installed. (:issue:`17613`)
- :meth:`DataFrame.assign` will preserve the original order of ``**kwargs`` for Python 3.6+ users instead of sorting the column names
- Implement interpolating ``NaT`` values in ``datetime`` series (:issue:`11701`)


.. _whatsnew_0210.api_breaking:
Expand Down
11 changes: 11 additions & 0 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
is_integer, is_integer_dtype,
is_float_dtype,
is_extension_type, is_datetimetz,
is_datetime64_dtype,
is_datetime64tz_dtype,
is_timedelta64_dtype,
is_list_like,
Expand All @@ -36,6 +37,7 @@
maybe_cast_to_datetime, maybe_castable)
from pandas.core.dtypes.missing import isna, notna, remove_na_arraylike

from pandas.core.tools.datetimes import to_datetime
from pandas.core.common import (is_bool_indexer,
_default_index,
_asarray_tuplesafe,
Expand Down Expand Up @@ -2734,6 +2736,15 @@ def from_csv(cls, path, sep=',', parse_dates=True, header=None,

return result

def interpolate(self, *args, **kwargs):
if (is_datetime64_dtype(self) or
is_datetime64tz_dtype(self)) and self.isnull().any():
s2 = self.astype('i8').astype('f8')
s2[self.isnull()] = np.nan
return to_datetime(s2.interpolate(*args, **kwargs))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you'll need to handle timezone information here. Once you do the .astype('i8') all TZ info is gone.

If someone has timezones, should it be tz_convert('UTC') -> interploate -> tz_localize("UTC") -> tz_convert(original)?

We'll want to test this around DST transitions...

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should not be done here at all, rather in pandas.core.missing.py

else:
return super(Series, self).interpolate(*args, **kwargs)

def to_csv(self, path=None, index=True, sep=",", na_rep='',
float_format=None, header=False, index_label=None,
mode='w', encoding=None, date_format=None, decimal='.'):
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/series/test_missing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1218,3 +1218,12 @@ def test_series_interpolate_intraday(self):
result = ts.reindex(new_index).interpolate(method='time')

tm.assert_numpy_array_equal(result.values, exp.values)

def test_series_interpolate_nat(self):
# GH 11701
for tz in [None, 'UTC', 'Europe/Paris']:
expected = pd.Series(pd.date_range('2015-01-01', '2015-01-30', tz=tz))
result = expected.copy()
result[[3, 4, 5, 13, 14, 15]] = pd.NaT
result = result.interpolate()
tm.assert_series_equal(result, expected)