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"