Skip to content

Commit 348fe13

Browse files
author
dcherian
committed
interp() now accepts date strings as desired co-ordinate locations
Fixes pydata#2284
1 parent 2fa9dde commit 348fe13

File tree

3 files changed

+19
-3
lines changed

3 files changed

+19
-3
lines changed

doc/interpolation.rst

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,14 +49,14 @@ array-like, which gives the interpolated result as an array.
4949
da.interp(time=[2.5, 3.5])
5050
5151
52-
To interpolate data with a :py:func:`numpy.datetime64` coordinate you have to
53-
wrap it explicitly in a :py:func:`numpy.datetime64` object.
52+
To interpolate data with a :py:func:`numpy.datetime64` coordinate you can either
53+
pass :py:func:`numpy.datetime64` objects or a date-string.
5454

5555
.. ipython:: python
5656
5757
da_dt64 = xr.DataArray([1, 3],
5858
[('time', pd.date_range('1/1/2000', '1/3/2000', periods=2))])
59-
da_dt64.interp(time=np.datetime64('2000-01-02'))
59+
da_dt64.interp(time='2000-01-02')
6060
6161
The interpolated data can be merged into the original :py:class:`~xarray.DataArray`
6262
by specifing the time periods required.

xarray/core/dataset.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1308,6 +1308,8 @@ def _validate_indexers(self, indexers):
13081308
""" Here we make sure
13091309
+ indexer has a valid keys
13101310
+ indexer is in a valid data type
1311+
* string indexers are cast to datetime64
1312+
if associated index is DatetimeIndex
13111313
"""
13121314
from .dataarray import DataArray
13131315

@@ -1328,6 +1330,12 @@ def _validate_indexers(self, indexers):
13281330
raise TypeError('cannot use a Dataset as an indexer')
13291331
else:
13301332
v = np.asarray(v)
1333+
1334+
if (v.dtype.kind == 'U'
1335+
and isinstance(self.coords[k].to_index(),
1336+
pd.DatetimeIndex)):
1337+
v = v.astype('datetime64[ns]')
1338+
13311339
if v.ndim == 0:
13321340
v = as_variable(v)
13331341
elif v.ndim == 1:

xarray/tests/test_interp.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -478,3 +478,11 @@ def test_datetime():
478478
0.5 * (da.isel(time=0) + da.isel(time=1)))
479479
assert_allclose(actual.isel(time=1).drop('time'),
480480
0.5 * (da.isel(time=1) + da.isel(time=2)))
481+
482+
x_new = np.array(['2000-01-01T12:00',
483+
'2000-01-02T12:00'])
484+
actual = da.interp(time=x_new)
485+
assert_allclose(actual.isel(time=0).drop('time'),
486+
0.5 * (da.isel(time=0) + da.isel(time=1)))
487+
assert_allclose(actual.isel(time=1).drop('time'),
488+
0.5 * (da.isel(time=1) + da.isel(time=2)))

0 commit comments

Comments
 (0)