def test_from_variables_index_adapter(self) -> None: # test index type is preserved when variable wraps a pd.Index data = pd.Series(["foo", "bar"], dtype="category") pd_idx = pd.Index(data) var = xr.Variable("x", pd_idx) index = PandasIndex.from_variables({"x": var}) assert isinstance(index.index, pd.CategoricalIndex)
def test_from_variables(self): var = xr.Variable("x", [1, 2, 3], attrs={"unit": "m"}, encoding={"dtype": np.int32}) index, index_vars = PandasIndex.from_variables({"x": var}) xr.testing.assert_identical(var.to_index_variable(), index_vars["x"]) assert index.dim == "x" assert index.index.equals(index_vars["x"].to_index()) var2 = xr.Variable(("x", "y"), [[1, 2, 3], [4, 5, 6]]) with pytest.raises(ValueError, match=r".*only accepts one variable.*"): PandasIndex.from_variables({"x": var, "foo": var2}) with pytest.raises(ValueError, match=r".*only accepts a 1-dimensional variable.*"): PandasIndex.from_variables({"foo": var2})
def test_from_variables(self) -> None: # pandas has only Float64Index but variable dtype should be preserved data = np.array([1.1, 2.2, 3.3], dtype=np.float32) var = xr.Variable("x", data, attrs={"unit": "m"}, encoding={"dtype": np.float64}) index = PandasIndex.from_variables({"x": var}) assert index.dim == "x" assert index.index.equals(pd.Index(data)) assert index.coord_dtype == data.dtype var2 = xr.Variable(("x", "y"), [[1, 2, 3], [4, 5, 6]]) with pytest.raises(ValueError, match=r".*only accepts one variable.*"): PandasIndex.from_variables({"x": var, "foo": var2}) with pytest.raises(ValueError, match=r".*only accepts a 1-dimensional variable.*"): PandasIndex.from_variables({"foo": var2})