From 47a632ac970bcca0fca3fe1f846e83478b39fbd3 Mon Sep 17 00:00:00 2001 From: Tim Heap Date: Thu, 11 May 2023 16:33:33 +1000 Subject: [PATCH 1/3] Use `numpy.can_cast` instead of casting and checking In numpy >= 1.24 unsafe casting raises a RuntimeWarning for an operation that xarray does often to check if casting is safe. `numpy.can_cast` looks like an alternative approach designed for this exact case. --- xarray/coding/times.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/xarray/coding/times.py b/xarray/coding/times.py index 3745d61acc0..ccf6c6638d2 100644 --- a/xarray/coding/times.py +++ b/xarray/coding/times.py @@ -615,9 +615,8 @@ def encode_datetime(d): def cast_to_int_if_safe(num) -> np.ndarray: - int_num = np.asarray(num, dtype=np.int64) - if (num == int_num).all(): - num = int_num + if np.can_cast(num, to=np.int64, casting='safe'): + return np.asarray(num, dtype=np.int64) return num From 915a215ff5a2ca45035ce31a63bc777ac7eb5d5e Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 11 May 2023 06:36:41 +0000 Subject: [PATCH 2/3] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- xarray/coding/times.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xarray/coding/times.py b/xarray/coding/times.py index ccf6c6638d2..a746f26385a 100644 --- a/xarray/coding/times.py +++ b/xarray/coding/times.py @@ -615,7 +615,7 @@ def encode_datetime(d): def cast_to_int_if_safe(num) -> np.ndarray: - if np.can_cast(num, to=np.int64, casting='safe'): + if np.can_cast(num, to=np.int64, casting="safe"): return np.asarray(num, dtype=np.int64) return num From 452156f6b116e719d7a3354e7b072d5b48729582 Mon Sep 17 00:00:00 2001 From: Tim Heap Date: Thu, 11 May 2023 16:38:45 +1000 Subject: [PATCH 3/3] Add note to whats-new.rst --- doc/whats-new.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/whats-new.rst b/doc/whats-new.rst index 45273d31ca5..d075a9a590e 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -44,6 +44,7 @@ Bug fixes By `Deepak Cherian `_. - Fix groupby sum, prod for all-NaN groups with ``flox``. (:issue:`7808`). By `Deepak Cherian `_. +- Use `numpy.can_cast` to avoid a RuntimeWarning from numpy. (:pull:`7834`). Documentation ~~~~~~~~~~~~~