Skip to content
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

re-add timedelta support for polyval #6599

Merged
merged 2 commits into from
May 12, 2022
Merged
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
6 changes: 5 additions & 1 deletion xarray/core/computation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1933,14 +1933,18 @@ def _ensure_numeric(data: T_Xarray) -> T_Xarray:
from .dataset import Dataset

def to_floatable(x: DataArray) -> DataArray:
if x.dtype.kind in "mM":
if x.dtype.kind == "M":
# datetimes
return x.copy(
data=datetime_to_numeric(
x.data,
offset=np.datetime64("1970-01-01"),
datetime_unit="ns",
),
)
elif x.dtype.kind == "m":
Copy link
Contributor

Choose a reason for hiding this comment

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

LGTM.

We also have another _floatize

def _floatize_x(x, new_x):
"""Make x and new_x float.
This is particularly useful for datetime dtype.
x, new_x: tuple of np.ndarray
"""
x = list(x)
new_x = list(new_x)
for i in range(len(x)):
if _contains_datetime_like_objects(x[i]):
# Scipy casts coordinates to np.float64, which is not accurate
# enough for datetime64 (uses 64bit integer).
# We assume that the most of the bits are used to represent the
# offset (min(x)) and the variation (x - min(x)) can be
# represented by float.
xmin = x[i].values.min()
x[i] = x[i]._to_numeric(offset=xmin, dtype=np.float64)
new_x[i] = new_x[i]._to_numeric(offset=xmin, dtype=np.float64)
return x, new_x

so it might be nice to harmonize in a future PR. For example, it seems like interp doesn't work with timedelta right now?

# timedeltas
return x.astype(float)
return x

if isinstance(data, Dataset):
Expand Down
8 changes: 8 additions & 0 deletions xarray/tests/test_computation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2010,6 +2010,14 @@ def test_where_attrs() -> None:
),
id="datetime",
),
pytest.param(
xr.DataArray(
np.array([1000, 2000, 3000], dtype="timedelta64[ns]"), dims="x"
),
xr.DataArray([0, 1], dims="degree", coords={"degree": [0, 1]}),
xr.DataArray([1000.0, 2000.0, 3000.0], dims="x"),
id="timedelta",
),
],
)
def test_polyval(
Expand Down