Skip to content

Commit e2a82d2

Browse files
committed
Add typecasting to prevent numpy 1.26.4 issue
1 parent 2f3d9e8 commit e2a82d2

File tree

1 file changed

+8
-9
lines changed

1 file changed

+8
-9
lines changed

cf_xarray/helpers.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -223,17 +223,16 @@ def _get_core_dim_orders(core_dim_coords: dict[str, np.ndarray]) -> dict[str, st
223223
for dim, coords in core_dim_coords.items():
224224
diffs = np.diff(coords)
225225

226-
# NOTE: This is added to prevent an issue with numpy 1.26.4 and Python
227-
# 3.11: numpy.core._exceptions._UFuncInputCastingError:
228-
# Cannot cast ufunc 'not_equal' input 0 from dtype('<m8[ns]') to dtype('<m8')
229-
# with casting rule 'same_kind'
230-
if np.issubdtype(coords.dtype, np.datetime64):
231-
zero = np.timedelta64(0, "ns")
226+
# Handle datetime64 and timedelta64 safely for both numpy 1.26.4 and numpy 2
227+
if np.issubdtype(coords.dtype, np.datetime64) or np.issubdtype(
228+
coords.dtype, np.timedelta64
229+
):
230+
# Cast to float64 for safe comparison
231+
diffs_float = diffs.astype("float64")
232+
nonzero_diffs = diffs_float[diffs_float != 0]
232233
else:
233234
zero = 0
234-
235-
# Ensure diffs and zero have the same dtype for comparison.
236-
nonzero_diffs = diffs[diffs != diffs.dtype.type(zero)]
235+
nonzero_diffs = diffs[diffs != zero]
237236

238237
if nonzero_diffs.size == 0:
239238
# All values are equal, treat as ascending

0 commit comments

Comments
 (0)