From 437e73be64b002c557b75a0cc2219f17dfc86d9c Mon Sep 17 00:00:00 2001 From: Maximilian Roos Date: Sun, 22 Sep 2024 22:54:37 -0700 Subject: [PATCH] Fix numpy 2.1 strings Not sure this is great, but it does seem to work? --- xarray/core/variable.py | 12 ++++++++++-- xarray/tests/test_variable.py | 9 +++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/xarray/core/variable.py b/xarray/core/variable.py index 9b9239cc042..9b15df63e1a 100644 --- a/xarray/core/variable.py +++ b/xarray/core/variable.py @@ -320,8 +320,16 @@ def convert_non_numpy_type(data): else: data = np.asarray(data) - if not isinstance(data, np.ndarray) and ( - hasattr(data, "__array_function__") or hasattr(data, "__array_namespace__") + if ( + not isinstance(data, np.ndarray) + and ( + hasattr(data, "__array_function__") or hasattr(data, "__array_namespace__") + ) + # Not exactly sure why this is a special case but + # https://github.com/pydata/xarray/issues/9535 + # (possibly numpy strings can be + # indexed but it's indexing the string rather than as an array?) + and not isinstance(data, np.str_) ): return cast("T_DuckArray", data) diff --git a/xarray/tests/test_variable.py b/xarray/tests/test_variable.py index 0a55b42f228..53a61c455c7 100644 --- a/xarray/tests/test_variable.py +++ b/xarray/tests/test_variable.py @@ -3068,3 +3068,12 @@ def test_pandas_indexing_adapter_non_nanosecond_conversion(index, dtype) -> None with pytest.warns(UserWarning, match="non-nanosecond precision"): var = Variable(["time"], data) assert var.dtype == np.dtype(f"{dtype}[ns]") + + +def test_numpy_strings(): + # https://github.com/pydata/xarray/issues/9535 + data = np.full((5,), fill_value="nothing") + da = DataArray(data) + values = np.asarray(["foo", "bar"]) + da[1:2] = values[0] + assert da.sel(dim_0=1).item() == "foo"